Typing the RenderView method in ASP.Net MVC

Since the first minutes I started playing around with the MVC framework something has bothered me about the use of magic strings in regards to the RendorView methods.

With the current implementation of RendorView there is NO compile time type checking to ensure that view even exists (evil magic strings). Also, there is no way to find all usages of a view without doing a 'global find' on the project.

If you can strongly type the view to be used you will benefit from compile time type checking, you can use ReSharpers 'Find Usages' and it is just less evil.

Here are 2 ways to do this:

1 - Generics
public virtual void RenderView<T>( object viewData )
{
RenderView(typeof(T).Name, string.Empty, viewData);
}

2 - Type provided
public virtual void RenderView(Type viewType, object viewData)
{
RenderView(viewType.Name, string.Empty, viewData);
}
Here are a few examples of code calling the new RendorView methods

1 - Generics

RenderView<SportsListing>(sports);

2 - Type provided

RenderView(typeof(SportsEdit), new SportsEditViewModel(sports));
Now if I change the name of my views, I will get a compile time error letting me know ALL the places the view was being used.

This is a GOOD thing.

Yorum Gönder

0 Yorumlar

Ad Code

Responsive Advertisement