gpt4 book ai didi

asp.net-mvc-4 - ASP.NET MVC4 模型未绑定(bind)

转载 作者:行者123 更新时间:2023-12-04 22:33:36 24 4
gpt4 key购买 nike

我有一个非常简单的 ASP.NET MVC4 页面。它正在为 CustomerModel 呈现一个编辑表单。表单显示正确,但是当我点击编辑并回发时,模型没有被绑定(bind)。相反,CustomerModel 的所有属性都保留为默认值。请注意,正在调用正确的 Controller 方法,所以这不是问题。

我可以看到名称与模型属性(ID、名称、描述)匹配的表单值,但模型没有设置它们。

想法?

这是模型:

public class CustomerModel
{
[Required]
public Guid Id;

[Required]
public string Name;

[Required]
public string Description;
}

这是相关的 Controller 方法:
    [HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(CustomerModel customerModel)
{
if (ModelState.IsValid)
{
//...Do stuff

return RedirectToAction("Index");
}

return View(customerModel);
}

最后,这是带有填充值的表单集合的屏幕截图:

enter image description here

最佳答案

您的模型具有公共(public)字段但没有公共(public)属性,这些不一样。

改成:

public class CustomerModel
{
[Required]
public Guid Id {get; set;}

[Required]
public string Name {get; set;}

[Required]
public string Description {get; set;}
}

默认的 MVC 模型绑定(bind)器将使用属性,而不是字段。

更多关于这里 - http://rightbrainleft.net/2011/02/default-mvc-model-binder-doesnt-like-fields/

关于asp.net-mvc-4 - ASP.NET MVC4 模型未绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14329006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com