Question

I am searching for a way to make an application helper that allows you to define methods that you can call in all the controllers views. In Rails you get that for free but how can I accomplish this in ASP.NET MVC with c#?

Was it helpful?

Solution

The usual way is by writing extension methods to HtmlHelper - for example:

public static string Script(this HtmlHelper html, string path)
{
    var filePath = VirtualPathUtility.ToAbsolute(path);
    return "<script type=\"text/javascript\" src=\"" + filePath
        + "\"></script>";
}

Now in the view you can use Html.Script("foo"); etc (since the standard view has an HtmlHelper member called Html). You can also write methods in a base-view, but the extension method approach appears to be the most common.

OTHER TIPS

I would suggest adding an extension method to the base controller class.

public static class ControllerExtensions
{
    public static string Summin(this Controller c)
    {
        return string.Empty;
    }
}

You can access the helper function in your controller:

  public class MyController : Controller
    {
        public ActionResult Index()
        {
            this.Summin();
            return View();
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top