这是为什么我在我的模型更新MVC3控制器内的值不会呈现在客户端上? [英] Why is a value that I update in my model inside an MVC3 controller not rendered on the client?

查看:93
本文介绍了这是为什么我在我的模型更新MVC3控制器内的值不会呈现在客户端上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器动作 UpdateCustomer(CustomerDto客户)返回一个 PartialViewResult 与模型,这也是一个 CustomerDto

I have a controller action UpdateCustomer(CustomerDto customer) that returns a PartialViewResult with a model that is also a CustomerDto:

[HttpPost]
public PartialViewResult UpdateCustomer(CustomerDto customer)
{
    CustomerDto updatedCustomer = _customerService.UpdateCustomer(customer);
    updatedCustomer.Name = "NotThePostedName";
    return PartialView("CustomerData", updatedCustomer);
}

在我看来,我有以下行:

In my view, I have the following line:

@Html.TextBoxFor(model => model.Name)

到目前为止,一切都很好。在我看来,我做了一个异步后这种操作方法,模型绑定不工作,我可以在数据库中更新客户。然后我想呈现的更新的客户到客户端。例如,我想在我的控制器来改变客户名称。然而,被渲染为的总是的从属性的发布客户,不是从 updatedCustomer

So far, so good. In my view I do an asynchronous post to this action method, the model binder does its work and I can update a customer in the database. Then I want to render the updated customer to the client. For example, I'd like to change the customer name in my controller. However, what gets rendered is always the properties from the posted customer, not the properties from updatedCustomer.

我决定在我的项目MVC3源$ C ​​$ C,看看到底发生了什么。这似乎是一个功能(错误?)MVC3的,它总是从 ViewData.ModelState 的价值,而不是从 ViewData.Model <值/ code>。

I decided to include the MVC3 source code in my project to see what really happens. It appears to be a feature (bug?) of MVC3 that it always takes the value from ViewData.ModelState instead of the value from ViewData.Model.

这发生在线路366-367 System.Web.Mvc.Html.InputExtensions

This happens at lines 366-367 of 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 (被张贴到控制器动作值)的旧值。

As you can see, attemptedValue comes from ModelState. It contains the old value for CustomerDto.Name (the value that was posted to the controller action).

如果这是一个特点,它为什么这样工作?而且是有办法解决吗?我希望,如果我更新我的模型,更新被渲染,不老的价值我张贴。

If this is a feature, why does it work this way? And is there a way to work around it? I would expect that if I update my model, the update gets rendered, not the old value I posted.

推荐答案

嗯,是它的一个特点(ModelState中的实际模型之前,请务必检查),可以清除的ModelState,或者你需要更新只值:

Well yes it's a feature (ModelState is always checked before actual Model), you can clear the ModelState, or update just the value you need:

ModelState["Name"].Value = updatedCustomer.Name;

这篇关于这是为什么我在我的模型更新MVC3控制器内的值不会呈现在客户端上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆