【问题标题】:ASP.NET MVC4 Model Not BindingASP.NET MVC4 模型未绑定
【发布时间】:2013-01-14 23:59:48
【问题描述】:

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

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

想法?

这是模型:

public class CustomerModel
{
    [Required] 
    public Guid Id;

    [Required]
    public string Name;

    [Required]
    public string Description;
}

这里是相关的控制器方法:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(CustomerModel customerModel)
    {
        if (ModelState.IsValid)
        {
            //...Do stuff

            return RedirectToAction("Index");
        }

        return View(customerModel);
    }

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

【问题讨论】:

  • 我没有在其中看到您的 AntiForgeryToken。
  • 您希望在哪里看到它?我在视图中有它,并且我在方法上有 validate 属性。
  • 它必须以您的形式出现,而不仅仅是在您的视图中。它必须在提交的表单集合值中。

标签: asp.net-mvc-4 model-binding


【解决方案1】:

你的模型有公共字段但没有公共属性,这些不一样。

改为:

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

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

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

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

在此处了解更多信息 - http://rightbrainleft.net/2011/02/default-mvc-model-binder-doesnt-like-fields/

【讨论】:

  • 哈!就是这样。可能永远不会抓住这一点。谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多