Starting with MVC2, messing around with a simple db and just using the index view to display the items like:
in the controller:
//
// GET: /Equipment/
public ActionResult Index()
{
return View(database.Artists.ToList());
}
then the auto generated code in the view:
<td> <%: item.ArtistID %> </td>
<td> <%: item.GenreID %> </td>
etc etc
In my example, its potential that this data hasn’t been filled up, so it may be null. Now when I tried to load the view I will get a NullReferenceException. So where would the code for this belong ?
I guess you could have an if statement in the view, though surely this is not where the logic should go. Should I create a html helper which just returns empty string if the value is null?
edit:
Thanks for the help.
I have another query. What if say I’m developing a index browse type page. At the moment im displaying all items on the one page but there are like 2k items. Is there a tutorial or example of how to split this up? I guess my index browse controller could just take a integer range value from the browser, then I just say display next 100
When you return the list of artists you need to check for null and return a New list of Artists.
This is best accomplished, IMO, by returning what is called a ViewModel.
then in your controller
Then your view inherits from
MyFormViewModelThen consider factoring out the logic in the cntroller that gets the artists and sets objects out to another layer
EDIT
The reason for the FormViewModel is because if you want to add other things to return to the view you simply extend the model making it very easy to add more partial views etc
EDIT 2
If you have a partial viwe call ArtistList which takes the full list of artists. It then simply itterates through the list of artists and renders another PV call say Artist which is given a single instance of artist.
Then you could do a simple check within the Artist partial view for a null.
Or you could check in the ArtistList partial view for a null record and render another PV called say NullArtist.