Tackling Magic Strings in ASP.NET MVC Controllers

As others have pointed out Asp.Net MVC is full of magic strings. We use magic strings to:

show which view to render:

return View("Index");

redirect to a different action:

return RedirectToAction("Index");

name form elements:

<%= Html.TextBox("PhoneNumber") %>

and for many other purposes.

How to Remove Magic Strings from ASP.NET MVC Controllers

In this post I will just deal with the controller. I will leave removing magic strings from views for another day.

Strongly-typed View(...) method

A strongly-typed view method can be implemented in a controller base class or as an extension method. First define the available views as an enumeration or as a static class.

    public enum ViewNames
    {
        Index, Product, Item
    }

Next define a new view method that uses the enum instead of magic strings. Here is the controller base class version.

    protected ActionResult View(ViewNames view, object model)
    {
        return View(view.ToString(), model);
    }

This new view method can then be used in a controller like this:

    public ActionResult Index()
    {
        return View(ViewNames.Index, model);
    }

 

Strongly-typed RedirectToAction(...) method

The easiest way to get a strongly typed RedirectToAction method is to reference MvcContrib. Then in your controller add using MvcContrib; and a strongly typed redirect to action method will be available. It is used like this:

    public ActionResult View()
    {
        return this.RedirectToAction<HomeController>(c => c.Index());
    }

That should be enough to get most of the magic string out of your ASP.NET MVC controllers. The benefits of doing this are that it removes a class of bugs caused by magic string typos and increases support for refactoring.

kick it on DotNetKicks.com


Comments

Comments are closed