如何在发送到视图之前修改控制器操作中的已发布表单数据?

gxc*_*rke 17 asp.net-mvc

我想在成功操作后呈现相同的视图(而不是使用RedirectToAction),但我需要修改呈现给该视图的模型数据.以下是一个人为的示例,演示了两种不起作用的方法:

    [AcceptVerbs("POST")]
    public ActionResult EditProduct(int id, [Bind(Include="UnitPrice, ProductName")]Product product) {
        NORTHWNDEntities entities = new NORTHWNDEntities();

        if (ModelState.IsValid) {
            var dbProduct = entities.ProductSet.First(p => p.ProductID == id);
            dbProduct.ProductName = product.ProductName;
            dbProduct.UnitPrice = product.UnitPrice;
            entities.SaveChanges();
        }

        /* Neither of these work */
        product.ProductName = "This has no effect";
        ViewData["ProductName"] = "This has no effect either";

        return View(product);
    }
Run Code Online (Sandbox Code Playgroud)

有谁知道实现这个的正确方法是什么?

gxc*_*rke 23

在进一步研究之后,我解释了为什么以下代码对Action没有影响:

product.ProductName = "This has no effect";
ViewData["ProductName"] = "This has no effect either";
Run Code Online (Sandbox Code Playgroud)

我的视图使用HTML助手:

<% Html.EditorFor(x => x.ProductName);
Run Code Online (Sandbox Code Playgroud)

尝试查找密钥时,HTML Helpers使用以下顺序优先级:

  1. ViewData.ModelState字典条目
  2. 模型属性(如果是强类型视图.此属性是View.ViewData.Model的快捷方式)
  3. ViewData字典条目

对于HTTP Post Actions,始终填充ModelState,因此直接修改Model(product.ProductName)或ViewData(ViewData ["ProductName"])无效.

如果确实需要直接修改ModelState,那么执行此操作的语法是:

ModelState.SetModelValue("ProductName", new ValueProviderResult("Your new value", "", CultureInfo.InvariantCulture));
Run Code Online (Sandbox Code Playgroud)

或者,要清除ModelState值:

ModelState.SetModelValue("ProductName", null);
Run Code Online (Sandbox Code Playgroud)

您可以创建扩展方法来简化语法:

public static class ModelStateDictionaryExtensions {
    public static void SetModelValue(this ModelStateDictionary modelState, string key, object rawValue) {
        modelState.SetModelValue(key, new ValueProviderResult(rawValue, String.Empty, CultureInfo.InvariantCulture));
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以简单地写:

ModelState.SetModelValue("ProductName", "Your new value");
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅MVC2视图中的数据消耗.

  • 谢谢,这非常有用.我用它来删除信用卡号码,在输入错误的信用卡号码后重新显示.我对这项任务的非平凡/非直观性感到惊讶. (2认同)