我有一个控制器动作UpdateCustomer(CustomerDto customer)
返回一个PartialViewResult
其模型也是CustomerDto
:
[HttpPost]
public PartialViewResult UpdateCustomer(CustomerDto customer)
{
CustomerDto updatedCustomer = _customerService.UpdateCustomer(customer);
updatedCustomer.Name = "NotThePostedName";
return PartialView("CustomerData", updatedCustomer);
}
在我看来,我有以下几行:
@Html.TextBoxFor(model => model.Name)
到目前为止,一切都很好。在我看来,我对此操作方法进行了异步发布,模型绑定器完成其工作,并且我可以更新数据库中的客户。然后我想渲染updated客户对客户。例如,我想更改控制器中的客户名称。然而,渲染出来的是always发布的属性customer
,不是来自的属性updatedCustomer
.
我决定将 MVC3 源代码包含在我的项目中,看看到底发生了什么。这似乎是 MVC3 的一个功能(bug?),它总是从中获取值ViewData.ModelState
而不是来自的值ViewData.Model
.
这发生在第 366-367 行System.Web.Mvc.Html.InputExtensions
:
string attemptedValue =
(string) htmlHelper.GetModelStateValue(fullName, typeof(string));
tagBuilder.MergeAttribute("value",
attemptedValue ?? ((useViewData)
? htmlHelper.EvalString(fullName)
: valueParameter), isExplicitValue);
如你看到的,attemptedValue
来自ModelState
。它包含旧值CustomerDto.Name
(发布到控制器操作的值)。
如果这是一个功能,为什么它会这样工作?有没有办法解决这个问题?我希望如果我更新模型,则会渲染更新,而不是我发布的旧值。