views:

126

answers:

2

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#?

+3  A: 

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.

Marc Gravell
A: 

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();
        }
    }
The way I interpreted it, it was wanted from the view, not the controller... not a big change, though.
Marc Gravell