MVC2 - The main question that logic should go on

Starting with MVC2, messing around with simple db and just use the index view to display elements such as:

in the controller:

// // GET: /Equipment/ public ActionResult Index() { return View(database.Artists.ToList()); } 

then the automatically generated code in the view:

  <td> <%: item.ArtistID %> </td> <td> <%: item.GenreID %> </td> 

etc.

In my example, its potential is that this data was not filled, so it can be zero. Now that I have tried loading the view, I will get a NullReferenceException. So where is the code for this?

I think you could have an if statement in the view, although of course this is not where the logic should go. Should I create an html helper that just returns an empty string if the value is null?

change

Thanks for the help.

I have another request. What if I say that I am developing a page such as index view. Currently im displays all elements on one page, but there are like 2k elements. Is there a tutorial or an example of how to share it? I think my list view controller can just take the integer range value from the browser, then I just say the following 100

+6
visual-studio visual-studio-2010 asp.net-mvc-2
source share
2 answers

When you return the artist list, you need to check the null value and return the new artist list.

This is best done IMO by returning what is called a ViewModel.

 Class MyFormViewModel List<Artist> artists {get; set;} 

then in your controller

 MyFormViewModel fvm = new MyFormViewModel(); fvm.artists = database.Artists.ToList(); if (fvm.artists == null) fvm.artists = new List<Artist>(); return View(fvm) 

Then your view is inherited from MyFormViewModel

Then consider the factorization of logic in cntroller, which receives artists and sets objects to another level.

EDIT

The reason for FormViewModel is that if you want to add other things to return to the view, you simply extend the model, making it easier to add more partial views, etc.

EDIT 2

If you have a partial call to ArtistList that accepts a complete list of artists. Then he simply iterates over the artist list and passes another PV call, saying Artist, which is given one instance of the artist.

Then you can do a simple check in the partial view of the Artist for null.

Or you can check the partial view of the ArtistList for a null record and display another PV called say NullArtist.

+3
source share

One option is to display another view that displays when no artist is found, for example. "Nothing found". In this case, the change will be in the controller.

Another option is to change the view so that it contains some code to visualize the message that no artist was found if the list is empty or displays the list.

You can always get a more complex look with the ViewModel if you need to later. There are simpler solutions at this point.

+2
source share

All Articles