Reputation: 1999
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#?
Upvotes: 1
Views: 772
Reputation:
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();
}
}
Upvotes: 0
Reputation: 1064244
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.
Upvotes: 3