开发者

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

开发者 https://www.devze.com 2023-02-05 05:08 出处:网络
If ModelState.IsValid==false, we should return View() or View(movie)? public ActionResult Create() { return View();

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

精彩评论

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