添加ModelState.AddModelError而不重新加载页面(mvc4)

时间:2014-11-24 16:10:14

标签: 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 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();
    }
}

基本上,我正在尝试保留用户在帖子方法

之前填写的所有数据

我尝试使用return RedirectToAction("Create");,但它总是刷新页面。

1 个答案:

答案 0 :(得分:1)

当您致电View时,您必须传回已发布的模型。你需要的是:

[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);
}