我想显示一个带有某些字段(示例中的一个)的表单,提交它,保存并显示同一页面并重置所有字段。当我提交问题时,我执行“保存”操作,但是当我显示视图时,表单仍然被填写。
该模型 :
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" />
}
何时调试视图,在“立即窗口”中Model.FirstName = ""
但是当页面显示时我仍然有发布的值。我尝试了一个ReditrectionToAction("Index")
在结束时Save
方法但结果相同。
你有好主意吗 ?
Thanks,
如果你想这样做,你需要清除 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);
}
或者直接重定向到索引GET
成功后采取的行动:
[HttpPost]
public ActionResult Save(TestingModel model)
{
//Save data to DB here ...
return RedirectToAction("Index");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)