Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid hard-coding controller and action names

ASP.NET MVC seems to be encouraging me to use hard-coded strings to refer to controllers and actions.

For example, in a controller:

return RedirectToAction("Index", "Home");

or, in a view:

Html.RenderPartial("Index", "Home");

I don't want hard-coded strings all over my code. What can I do to avoid this?

like image 219
kristian Avatar asked Jun 30 '11 09:06

kristian


1 Answers

It sounds to me like you want to use strongly typed redirects. I made a static helper class called RedirectionHelper that has the following method:

public static string GetUrl<T>(Expression<Action<T>> action, RequestContext requestContext, RouteValueDictionary values = null) where T : Controller
{
    UrlHelper urlHelper = new UrlHelper(requestContext);
    RouteValueDictionary routeValues = ExpressionHelper.GetRouteValuesFromExpression(action);

    if (values != null)
        foreach (var value in values)
            routeValues.Add(value.Key, value.Value);

    return urlHelper.RouteUrl(routeValues);
}

The only caveat is that you will have to use the Microsoft.Web.Mvc futures library available out on Nuget.

Now, for your controller, create a base controller that all controllers inherit from that has this method:

protected RedirectResult RedirectToAction<T>(Expression<Action<T>> action, RouteValueDictionary values = null) where T : Controller
{
    return new RedirectResult(RedirectionHelper.GetUrl(action, Request.RequestContext, values));
}

Now, in your action, all you have to do is say:

return RedirectToAction<Controller>(x => x.Index());

Likewise, you can write a html extension method that takes in the same parameters and builds your anchor tag.

Like you said above that you wanted, when you change Controller or Action names, your project will break at compile time and show you where the breaks occur. However, this will only occur in the controllers, seeing as how the views don't compile.

Hope this helps!

like image 115
mccow002 Avatar answered Sep 28 '22 10:09

mccow002