C# 添加ModelState.AddModelError而不重新加载页面(mvc4)
我正在使用MVC4,我的控制器中有两种方法: 获取方法C# 添加ModelState.AddModelError而不重新加载页面(mvc4),c#,.net,asp.net-mvc-4,C#,.net,Asp.net Mvc 4,我正在使用MVC4,我的控制器中有两种方法: 获取方法 public ActionResult Create() { var vm = new User { Client= new Catastro_Cliente() Genre = ClienteRepository.GetGenres(), Type= ClienteRepository.GetTypes() }; ViewBag.Genre = new Se
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);
}
[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();
}
}
发布方法
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);
}
[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();
}
}
基本上,我试图保留用户在post方法之前填写的所有数据
我尝试了
返回重定向到操作(“创建”)
但它总是刷新页面。调用视图时,您必须传回发布的模型。您需要的是:
[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);
}
你的意思是想在if(Validator(client.document)){…}
?@Rhumborl是的,但是我不需要重新加载页面来将客户端信息保留在表单上