开发者

If `ModelState.IsValid==false`, we should return `View()` or `View(movie)`?

If ModelState.IsValid==false, we should return View() or View(movie)?

    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Movie movie)
    {
        if (ModelState.IsValid)
        {
            context.Movies.Add(movie);
            context.SaveChanges();
      开发者_如何学Python      return RedirectToAction("Index");
        }
        else
        {
            return View();
        }
    }

or

    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Movie movie)
    {
        if (ModelState.IsValid)
        {
            context.Movies.Add(movie);
            context.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            return View(movie);
        }
    }

?


Depends if you want to clear the form or not.

Returning the Model will place the values the user entered back into the form where returning view() will display an empty form on post back.


Always return the same model when validation fails (return View(movie); )


What I like to do is:

[HttpPost]
public ActionResult Create(Movie movie)
{
   this.ViewData.Model = movie;
...

That way I can return View() without worrying about passing the model as argument. There can be more than one situation where you may want to return the view, e.g. try/catch around SaveChanges(). This also gives you the chance to handle errors on the OnException method and return a view without losing the model.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜