views:

248

answers:

2

Scenario: I have a page which contains a dropdownlist and a table which contains a list of details based on the value selected in the dropdownlist when the dropdown is changed.

Now at first instance when the page is loaded, the dropdownlist contains a blank value followed by other values. So for the first time there won't be any values in the 'model' object and so when rendering data, say 'model.ID', it will fail because 'model' is null.

Currently I am handling this scenario by writing this bit of code in the aspx page

if (Model != null)
{
   //DisplayData
   Model.ID
}

Is this the right way to do it or is there a more elegant way in MVC?

+2  A: 

I would consider handing your view a new, empty model if you can, rather than null. This will save you from having to have null checks everywhere, and really, what's a View without a model?

If that's not possible (your model is complex and has non-nullable fields that you don't want to display), then consider changing the workflow of the page so that the part displaying the model (perhaps a partial view) isn't shown until after the user makes the initial selection.

If that's not possible either, then really, I wouldn't say that there is much wrong with your approach other than it's tedious to program.

womp
A: 

I think the more elegant way is working with "default" or "empty" Model:

<%= (Model ?? new Model()).Id &>
eu-ge-ne