views:

27

answers:

1

In my controller, I check for a articleID in the querystring, if it is present, I will render the edit view page, otherwise I will render the add view page.

Now in my edit page, there are times when certain classes in my ViewData might be null.

Put I want to pre-populate textboxes in the edit page.

How can I prepopulate text into fields, but at the same time safe guard against a null object/property?

+1  A: 

The type-safe option is to define two ViewModels instead of one. One for the Add page and one for the Edit page. If they have a lot of common data that is guaranteed never to be null, you can implement those properties on a common base class, but that is not necessary.

When you decide to show the Add view, you return a ViewResult with the appropriate ViewModel.

When you decide to show the Edit view, you return a ViewResult with that ViewModel.

Each View can then be a strongly typed view based on exactly that ViewModel type.

This other SO answer elaborates a bit on that approach.

Mark Seemann
the problem with this approach, if I have 3 view pages I have to maintain all 3 of them! i.e. adding a textbox to one, means 3 changes to worry about etc.
mrblah
As I wrote in the other answer, you can use a shared View (.ascx) for the common data, so that you only need to maintain it in one place.
Mark Seemann