asp.net – MVC3:如何强制Html.TextBoxFor使用模型值而不是POSTed值

在许多情况下,我遇到了一个问题,即我在服务器上创建了一个模型,作为返回值的结果.处理模型后,会更改某些模型值,然后在页面上重新显示.是否有一些简单的方法来覆盖导致MVC框架使用POSTed值而不是我的模型值的行为.

例:

模型

public class MyModel {
    public string Value1 { get; set; }
}

调节器

public MyController : Controller {
    public ActionResult MyAction() {
        var model = new MyModel();
        model.Value1 = "OldValue";
        return View(model);
    }
    [HttpPost]
    public ActionResult MyAction(MyModel model) {
        model.Value1 = "NewValue";
        return View(model);
    }
}

视图

@using(Html.BeginForm("MyAction","My",FormMethod.Post) {
    @Html.TextBoxFor(m => m.Value1)
    <input type="submit"/>
}

首次加载此页面时,文本框将包含“OldValue”.单击提交后,文本框仍然包含“OldValue”,因为这是POST回服务器的内容,但我希望它使用模型中的值(NewValue)创建第二页(在POST之后).

有没有一种简单的方法告诉M​​VC这样做?我不确定在这种情况下我应该做些什么才能得到我想要的结果.

注意 – 这都是伪代码,所以我可能会有一些错误,但概念应该存在.

解决方法

在您的帖子重定向(后 – 重定向获取模式).

[HttpPost]
public ActionResult MyAction(MyModel model) {
    model.Value1 = "NewValue";
    return RedirectToAction("MyAction");
}

编辑

清除模型状态以传回已编辑的模型

[HttpPost]
    public ActionResult MyAction(MyModel model)
    {
        var newModel = new MyModel();
        newModel = model;
        ModelState.Clear();
        newModel.Value1 = "NewValue";
        return View(newModel);
    }

相关文章

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