asp.net-mvc – 保存后显示相同的页面

我想显示一个带有某个字段的表单(示例中有一个),提交它,保存并显示同一页面并重置所有字段.我提交时的问题,我进行“保存”操作,但是当我显示视图时,表单仍然填写.

该模型 :

public class TestingModel
{
    public string FirstName { get; set; }
}

控制器:

public class ChildController : Controller
{
    public ActionResult Index()
    {
        TestingModel model = new TestingModel();
        return View(model);
    }

    public ActionResult Save(TestingModel model)
    {
         Console.WriteLine(model.FirstName); //OK

        //Save data to DB here ...          

        TestingModel testingModel = new TestingModel() { FirstName = string.Empty };
        return View("Index",testingModel);
    }
}

风景 :

@using (Html.BeginForm("Save","Child",FormMethod.Post))
{
    @Html.TextBoxFor( m => m.FirstName)
   <input type="submit" id="btSave" />
}

当Id调试到视图时,在“Immediat窗口”Model.FirstName =“”但是当页面显示时,我仍然发布了值.我在Save方法的末尾尝试了ReditrectionToAction(“Index”)但结果相同.

你有好主意吗 ?

谢谢,

解决方法

如果你想这样做,你需要清除ModelState中的所有内容.否则,HTML帮助程序将完全忽略您的模型,并在绑定其值时使用ModelState中的数据.

像这样:

[HttpPost]
public ActionResult Save(TestingModel model)
{
    //Save data to DB here ...          

    ModelState.Clear();
    TestingModel testingModel = new TestingModel() { FirstName = string.Empty };
    return View("Index",testingModel);
}

或者只是在成功的情况下重定向到Index GET操作:

[HttpPost]
public ActionResult Save(TestingModel model)
{
    //Save data to DB here ...          
    return RedirectToAction("Index");
}

相关文章

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