0
//
// GET: /Movies/Edit/5

public ActionResult Edit(int id = 0)
{
    Movie movie = db.Movies.Find(id);
    if (movie == null)
    {
        return HttpNotFound();
    }
    return View(movie);
}

//
// POST: /Movies/Edit/5

[HttpPost]
public ActionResult Edit(Movie movie)
{
    if (ModelState.IsValid)
    {
        db.Entry(movie).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(movie);
}

In my understanding, HttpPost is only accessible by posting the populated form in the corresponding view. My confusion is whether or not I need to check the nullness of movie in HttpPost as I think movie has no chance to be null. What do you think of it? Is there a chance in which movie is null?

Please wisely downvote my question by giving the reason!

kiss my armpit
  • 3,413
  • 1
  • 27
  • 50

2 Answers2

1

Yes movie could be null, so you should check for it. Take for example the following AJAX call:

$.ajax({

    type: "POST",
    url: "Home/Edit",
    async: false,
    data: {},
    success: function (data, text) {
        // do something
    },
    error: function (request, status, error) {
        //do something
    }
});

In this case, Movie will be null and you should account for that in your code by checking for null:

public ActionResult Edit(Movie movie)
{
   if (movie == null)
   {
        // Return a different view or perform a redirect
   }

   //... The rest of your code
}
John Koerner
  • 37,428
  • 8
  • 84
  • 134
  • For the normal scenario without Ajax call (I have NOT learnt Ajax for sure), is it still necessary to check the nullness of `movie`? – kiss my armpit Jun 18 '13 at 13:44
  • How will the rest of your code behave if it is null? Will it crash? Will it bring down the entire application? In a web app, just because your UI doesn't expose it doesn't mean someone can't use fiddler, browser dev tools or direct ajax calls to call your methods. If these methods corrupt data or crash the entire system, someone could cause you many problems if they are malicious. – John Koerner Jun 18 '13 at 20:02
0

ModelState.IsValid tells only you if any model errors have been added to ModelState not if the Model contains NULL references.

public ActionResult Edit(Movie movie)
{
    if(movie == null)
    {
        // or what else you what...
        return View();
    }

    if (ModelState.IsValid)
    {
        db.Entry(movie).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(movie);
}
  • 1
    @ArtificialStupidity https://stackoverflow.com/questions/881281/what-is-modelstate-isvalid-valid-for-in-asp-net-mvc-in-nerddinner and https://stackoverflow.com/questions/36893804/what-does-modelstate-isvalid-do – Smartis has left SO again Oct 04 '17 at 05:58