今天在 MVC 中遇到了一个非常奇怪的错误。我不想发布我的所有代码,但我会发布一个小例子。
假设我有一个 cshtml 页面,其中包含一个表单:
@model UserValidation
<!-- Code before body -->
@using (Html.BeginForm("UpdateUser", "Account"))
{
<div class="Label">@Html.LabelFor(m => m.Name):</div>
<div>@Html.TextBoxFor(x => x.Name)</div>
<div style="clear: both;">
@Html.ValidationMessageFor(x => x.Name)
<div class="Label">@Html.LabelFor(x => x.OldPass):</div>
<div>@Html.PasswordFor(x => x.OldPass)</div>
<div style="clear: both;">
@Html.ValidationMessageFor(x => x.OldPass)
<!-- More Form Code Here, You get the idea -->
<input type="submit" value="Submit" />
}
以及验证类(我不确定这是否是问题的一部分)
public class UserValidation
{
[Display(Name = "User Name")]
public string Name { get; set; }
[Display(Name = "Current password")]
public string OldPass { get; set; }
//More code here
}
最后, Controller 中的 HTTPPOST:
[HttpPost]
public ActionResult UpdateInfo(UserValidation message)
{
//Code
if(message == null)
{
return null; //If param name == message this line is hit
}
return View();
}
如果 UpdateInfo
的参数是“message”或“Message”(仅据我所知),MVC 将无法反序列化该对象,并且它始终等于 空
。但是,如果我们只是更改参数对象的名称,它将包含正确的表单数据:
[HttpPost]
public ActionResult UpdateInfo(UserValidation newUserInfo)
{
//Code
if(newUserInfo == null)
{
return null;
}
return View(); //Param name != message, this line is hit
}
同样,只有当对象等于“message”或“Message”时才会发生这种情况。我不知道为什么会这样。
有人有理由这样做吗?
最佳答案
我猜您的 UserValidation
类上有一个名为 Message
的属性。
这会让模型绑定(bind)器感到困惑,因为它首先尝试将发布的值与参数名称进行匹配,然后才开始匹配复杂参数类型的属性。
在您的情况下,它会在您发布的数据中看到一个 Message
键,因此它会尝试匹配您的整个 UserValidation message
参数,该参数将失败,因此整个绑定(bind)过程将停止,您获取null
。
我只发现了一些关于此“功能”的非正式提及:
- Default Model Binding: ActionMethod Parameter name must not equal Model Property name?
- MVC3 - Model Property Name and Action Parameter Name - Fight!
因此只需使用不同的参数名称即可正常工作。
关于c# - MVC 4 "Bug"名为 "Message/message"的参数对象将不会被反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18644475/