【问题标题】:I change the model values in the controller but the view receives the model with the old values我更改了控制器中的模型值,但视图接收到具有旧值的模型
【发布时间】:2014-10-07 14:49:43
【问题描述】:

我有这个动作:

//Edit
[HttpPost]
public ActionResult InvoiceType(clsInvoiceType Model, string Stade)
{
    Model.Stade = Stade== "1" ? true : false;
    return PartialView(Model);
}

在此操作中,我尝试更改 Model.Stade 的值并返回模型,但视图始终接收发送到此操作的值,问题是我尝试在操作中更改模型的值并返回视图的新模型值但视图接收原始模型值所以我的更改不起作用,有什么问题?

如何更改原始模型值并将它们发送到视图?

【问题讨论】:

  • 只要把断点放到这个动作中,一步步观察会发生什么。
  • 可能是返回的缓存数据?向我们展示您调用 ActionResult InvoiceType 的标记。
  • 我做到了,在操作中值发生了变化,但是当模型被发送到视图时会收到原始值,所以我的更改不起作用
  • 这是我调用操作的代码:
  • function Edit(Id) { var row = jQuery("#Grid").jqGrid('getRowData', Id); $("#Detail").load('@Url.Action("/" + "TipoFactura", "TipoFactura")', row); };

标签: c# asp.net-mvc


【解决方案1】:

ModelState 对象包含回传到您的操作方法的值。在查看模型中的实际值之前,您视图中的 Html.*For() 辅助方法将始终从 ModelState 中提取值。如果您想更改一个值,您需要从ModelState 中删除发布的值。

[HttpPost]
public ActionResult InvoiceType(clsInvoiceType Model, string Stade)
{
    this.ModelState.Remove("Stade");  // or .Clear() to remove all keys
    Model.Stade = Stade== "1" ? true : false;
    return PartialView(Model);
}

【讨论】:

  • 谢谢,这项工作,但这条线 this.ModelState.Remove("Stade") 会产生帮助者的问题?例如,如果视图有一个使用此值的助手,助手可以获取它吗?
  • 不,帮助器在填充值时,将首先在 ModelState 集合中查找键的值,如果在 ModelState 集合中找不到,那么它将从模型对象中提取值.
【解决方案2】:

您可能应该通过以下方式禁用缓存:

[OutputCache(Duration=0, VaryByParam="none")]
[HttpPost]
public ActionResult InvoiceType(clsInvoiceType Model, string Stade)
{
    Model.Stade = Stade== "1" ? true : false;
    return PartialView(Model);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-25
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多