0

This is my first application in MVC.

I want to check whether list property named movies, of object model, has a value or not. So that if a user attempts to find details of a movie and that movie doesn't exist he should get an error.

Lets say, movies list only has data for two movies, but user attempts to access: /Movie/Details/3 or /Movie/Details/abc

I want to handle such invalid requests.

MovieController

public class MovieController : Controller
{
    MovieCustomerViewModel model = new MovieCustomerViewModel();

    // GET: Movie
    public ActionResult Index()
    {
        model.movies = new List<Movie>
        {
            new Movie{id=1,name="Shrek"},
            new Movie{id=1,name="Wall-e"}
        };
        return View(model);
    }


    public ActionResult Details(int? id)
    {
        if (id < 1 || id > 2 || !id.HasValue || model.movies.Count==0)
            return HttpNotFound();
        else
            return View();
    }

}

One simple way is to use the Count property of List, but it throws NullReferenceException.

enter image description here

This tells me that model has been re-instantiated and the values assigned in Index are limited to that action only. As a beginner, I don't understand what to do then..

-I can use a constructor for assigning values, but I am not sure about it. Is it a good approach?

-Can this problem be solved with Route attributes?

-Am I missing something about Action attributes or Route attributes at this stage of learning?

Thanks in advance.

Junaid
  • 941
  • 2
  • 14
  • 38
  • Your requirement is not clear! Is database not involved in this case? – TanvirArjel Dec 21 '18 at 03:15
  • @TanvirArjel No. Database is not involved. The object 'model' has two data members, one is 'movies' list and the other is 'customers' list. If I try to access data of movies and the list 'movies' is empty, an error should be returned, but this program throws an exception. Hope you got my point.. – Junaid Dec 21 '18 at 07:37
  • 1
    Check if `model.movies==null` before doing anything in `Details`. Also, you're very lucky that this question has not been marked as duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – ikerbera Dec 21 '18 at 09:04

0 Answers0