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#?
From stackoverflow
-
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 anHtmlHelpermember calledHtml). You can also write methods in a base-view, but the extension method approach appears to be the most common. -
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(); } }Marc Gravell : The way I interpreted it, it was wanted from the view, not the controller... not a big change, though.
0 comments:
Post a Comment