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.
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.