.NET中如何获取表单所有输入值并创建新客户
表单提交与Action参数绑定解决方案
你当前的HTML表单默认以application/x-www-form-urlencoded格式发送键值对,但后端Action使用[FromBody] string value尝试读取原始请求体内容,两者格式不兼容,所以无法获取输入框的值。下面是两种可行的解决方式:
方案一:使用模型绑定(推荐)
这种方式更符合ASP.NET Core的最佳实践,便于后续扩展维护。
1. 创建Customer模型类
添加一个与表单字段对应的实体类:
public class Customer { public string CustomerID { get; set; } public string CustomerName { get; set; } public string ContactName { get; set; } public string Address { get; set; } // 注意修正表单里的"adress"拼写为"Address" public string City { get; set; } public string PostalCode { get; set; } public string Country { get; set; } }
2. 调整后端Action
移除[FromBody]特性,直接接收Customer模型参数,框架会自动完成表单字段到模型属性的绑定:
[HttpPost] [ActionName("Simple")] public IActionResult AddCustomer(Customer customer) { // 直接使用customer对象的属性值,例如customer.CustomerID、customer.CustomerName // 这里编写创建新客户的业务逻辑(如保存到数据库) return Ok("客户创建成功"); }
3. 修正表单的action和字段名
表单的action要与ActionName一致,同时修正输入框的name属性拼写:
@{ViewData["Title"] = "Add new customer";} <h1>Add new customer</h1> <form method="post" action="Simple"> <input name="CustomerID" placeholder="Add customer ID"/> <input name="CustomerName" placeholder="Add customer name"/> <input name="ContactName" placeholder="Add contact name"/> <input name="Address" placeholder="Add address"/> <input name="City" placeholder="Add city"/> <input name="PostalCode" placeholder="Add postal code"/> <input name="Country" placeholder="Add country"/> <input type="submit" value="Create Customer"/> </form>
方案二:使用[FromForm]绑定单个字段
如果不需要创建模型,也可以给每个参数添加[FromForm]特性,直接绑定表单字段:
[HttpPost] [ActionName("Simple")] public IActionResult AddCustomer( [FromForm] string customerID, [FromForm] string customerName, [FromForm] string contactName, [FromForm] string address, [FromForm] string city, [FromForm] string postalCode, [FromForm] string country) { // 直接使用各个参数值执行创建逻辑 return Ok("客户创建成功"); }
此时表单的输入框name属性需与参数名保持一致(大小写不敏感,但建议统一)。
关键注意事项
- 表单中
adress的拼写错误会导致绑定失败,务必修正为address - 确保表单的action属性与Action的
[ActionName]或路由规则匹配,否则请求会找不到对应的Action - 若需以JSON格式提交数据,可改用AJAX方式,但传统表单提交使用上述方案更直接
内容的提问来源于stack exchange,提问作者Aleksandre Geladze
相关产品推荐
相关产品推荐

