Thursday, 13 November 2008

Strongly typed View Names

I like the MVC framework but I want to type

public ActionResult Index()
{
    return View(Views.Home.Index);
}

Instead of

public ActionResult Index()
{
     return View("Index");
}

So that my code is strongly typed.  I don’t use View() by itself because in unit testing I want to be sure my controller is returning the correct view.  Well I’ve found a nice way to do it.  If you don’t have a base controller you’ll need one, like so:

public class BaseController : Controller
{
    protected ActionResult View(Type viewType, object viewData)
    {
        return (View(viewType.Name, viewData));
    }
 
    protected ActionResult View(Type viewType)
    {
        return (View(viewType.Name));
    }
}

This will take the view name from the strongly typed reference to the class when you pass it by type and allow you to return your views like this:

public ActionResult Index()
{
    return View(typeof(Views.en.Home.index));
}
 
public ActionResult About()
{
    return View(typeof(Views.en.Home.about), AboutModel);
}

This is compile time checking and will save you from misspelling the view name (even if you unit test this can happen, particularly if you’re familiar with the dreaded copy and paste).

3 comments:

Anonymous said...

http://stackoverflow.com/questions/474065/strongly-typing-asp-net-controller-view-method-for-model-type#474418

With a bit more work, you can have the model strongly typed too.

erectile dysfunction causes said...

Greate article. Keep posting such kind of information on your blog. Im really impressed by your blog.
Hi there, You've done a fantastic job. I will certainly digg it and personally suggest to my friends. I am sure they will be benefited from this website.

impotence said...

We are a gaggle of volunteers and starting a new scheme in our community. Your web site offered us with useful information to work on. You have done an impressive task and our whole group will probably be grateful to you.