[英]Add ModelState.AddModelError without reload the page (mvc4)
I'm using MVC4 and I have 2 methods in my controller: 我正在使用MVC4,控制器中有2种方法:
Get Method 获取方法
public ActionResult Create()
{
var vm = new User
{
Client= new Catastro_Cliente()
Genre = ClienteRepository.GetGenres(),
Type= ClienteRepository.GetTypes()
};
ViewBag.Genre = new SelectList(vm.Genre, "IdGenre", "Genre");
ViewBag.Type= new SelectList(vm.Type, "IdType", "Type");
return View(vm);
}
Post Method 过帐方法
[HttpPost]
public ActionResult CrearUsuario(Catastro_Cliente client)
{
if(Validator(client.document))
{
ModelState.AddModelError("NoDocument", "The document is invalid or not registered");
}
if(ModelState.IsValid)
{
return View();
}
}
Basically, I'm trying keep all the data that the user filled in before the post Method, 基本上,我正在尝试保留用户在post Method之前填写的所有数据,
I tried with return RedirectToAction("Create");
我尝试使用return RedirectToAction("Create");
but it always refreshes the page. 但它总是刷新页面。
You have to pass back the posted model when you call View
. 调用View
时,您必须传递回已发布的模型。 What you need is something like: 您需要的是这样的:
[HttpPost]
public ActionResult CrearUsuario(Catastro_Cliente client)
{
if(Validator(client.document))
{
ModelState.AddModelError("NoDocument", "The document is invalid or not registered");
}
if(ModelState.IsValid)
{
// save to database of whatever
// this is a successful response
return RedirectToAction("Index");
}
// There's some error so return view with posted data:
return View(client);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.