加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 为什么我在MVC3控制器中的模型中更新的值没有在

发布时间:2020-12-16 06:58:30 所属栏目:asp.Net 来源:网络整理
导读:我有一个控制器操作UpdateCustomer(CustomerDto customer),它返回一个PartialViewResult,其模型也是CustomerDto: [HttpPost]public PartialViewResult UpdateCustomer(CustomerDto customer){ CustomerDto updatedCustomer = _customerService.UpdateCustom
我有一个控制器操作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)

到现在为止还挺好.在我看来,我对这个动作方法进行了异步发布,模型绑定器完成了它的工作,我可以更新数据库中的客户.然后我想将更新的客户呈现给客户.例如,我想更改控制器中的客户名称.但是,呈现的内容始终是发布的客户的属性,而不是来自updatedCustomer的属性.

我决定在我的项目中包含MVC3源代码,看看到底发生了什么.它似乎是MVC3的一个特性(bug?),它始终从ViewData.ModelState获取值而不是ViewData.Model中的值.

这发生在System.Web.Mvc.Html.InputExtensions的第366-367行:

string attemptedValue =
    (string) htmlHelper.GetModelStateValue(fullName,typeof(string));
tagBuilder.MergeAttribute("value",attemptedValue ?? ((useViewData)
        ? htmlHelper.EvalString(fullName)
        : valueParameter),isExplicitValue);

如您所见,attemptValue来自ModelState.它包含CustomerDto.Name的旧值(发布到控制器操作的值).

如果这是一个功能,为什么这样做?有没有办法解决它?我希望如果我更新我的模型,会更新更新,而不是我发布的旧值.

解决方法

是的,它是一个功能(ModelState始终在实际模型之前检查),您可以清除ModelState,或只更新您需要的值:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读