Perhaps this is a question for Programmers - I'm sure someone will advise me if so.
When using MVC, I can also access the Html Helper variable and use whatever extension methods are defined, either the .Net ones or ones I might have specified myself.
@Html.Raw("<h1>This is my HTML</h1>")
How is this achieved? Say I wanted to add a separate object for another reason and have it available to all views in my MVC app?
I know I can't add it to the controller, as one view might be accessed by several controllers.
So my best guess is needing to subclass IView?
Edit: sorry - I didn't explain myself. At least I think...
I want the object to be available, but also instantiated. So for example, say I had an object called glosrob
, with a method SayHello()
and wanted to be able use it thusly:
@glosrob.SayHello()
Essentially I want to avoid having to add code to construct the object on each view e.g. avoid this
@{
var glosrob = new Glosrob();
}
How is Html helper 'available' to all views in MVC?
Inside your views folder you will find a separate web.config file. In the config file will be the class that all views derive from:
<pages pageBaseType="System.Web.Mvc.WebViewPage">
So all views derive from WebViewPage class which contains a property called Html that exposes the HtmlHelper.
Say I wanted to add a separate object for another reason and have it available to all views in my MVC app?
If you want your own custom property exposed you should read up on Changing Base Type Of A Razor View.
First you create your own class with your own property:
public abstract class CustomWebViewPage : WebViewPage {
public Glosrob Glosrob { get; set; }
public override void InitHelpers() {
base.InitHelpers();
Glosrob = new Glosrob ();
}
}
And update your config:
<pages pageBaseType="MyProject.Web.CustomWebViewPage">
Then you can call it in your view:
@Glosrob.SomeMethod();
Well you have a couple of options. You could put your Html Helper class in the System.Web.Mvc namespace like
namespace System.Web.Mvc
{
public static class HtmlExtensions
{
You could also import the namespace on each page:
<%@ Import Namespace="MvcApplication1.Helpers" %>
Or you could register in the web.config
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="MyHelper"/>
</namespaces>
Also check this as a possible duplicate: Import Namespace for Razor View
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With