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);
    }

有没有人知道正确的方法是完成这个?

解决方法

在进一步研究之后,我有一个解释为什么以下代码在Action中没有影响:
product.ProductName = "This has no effect";
ViewData["ProductName"] = "This has no effect either";

我的视图使用HTML助手:

<% Html.EditorFor(x => x.ProductName);

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

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

对于HTTP Post Actions,始终填充ModelState,因此直接修改Model(product.ProductName)或ViewData(ViewData [“ProductName”])没有任何作用.

如果您确实需要直接修改ModelState,这样做的语法是:

ModelState.SetModelValue("ProductName",new ValueProviderResult("Your new value","",CultureInfo.InvariantCulture));

或者,要清除ModelState值:

ModelState.SetModelValue("ProductName",null);

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

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));
    }
}

那么你可以简单地写:

ModelState.SetModelValue("ProductName","Your new value");

有关详细信息,请参阅Consumption of Data in MVC2 Views.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....