My View inherits Models.MyModel
<%@ Page Language="C#" MasterPageFile="Something.Master" Inherits="Models.MyModel>" %>
I need a property Model.Something
to be available in a HtmlHelper
method when I call it from this view.
<%= Html.CustomHelper(...) %>
Is there any way to access this? Maybe via ViewContext
or ViewDataDictionary
?
I do not want to explicitly pass Model.SessionKey
for each helper I call. Is there any approach that I missed? Or is this impossible.
Thanks.
Right-click in the Store Index action method and select Add View as before, select Genre as the Model class, and press the Add button. This tells the Razor view engine that it will be working with a model object that can hold several Genre objects.
It binds the model object to HTML controls to display the value of model properties into those controls and also assigns the value of the controls to the model properties while submitting a web form. So always use the HtmlHelper class in razor view instead of writing HTML tags manually.
This process determines which view file is used based on the view name. The default behavior of the View method ( return View(); ) is to return a view with the same name as the action method from which it's called.
My approach to this would be to have the all the models that you want to use with this helper implement an interface that defines their common properties. The ViewData property on the HtmlHelper object has a Model property (of type object
). Inside your helper, you can cast this as the interface type. Assuming that it is non-null at that point, i.e., actually not null and of the correct type, you can then use the common properties.
public static string CustomerHelper( this HtmlHelper helper, ... )
{
var model = helper.ViewData.Model as ISessionModel;
var sessionKey = model.SessionKey;
...
}
Similarly you can do this:
public static string CustomerHelper( this HtmlHelper helper, ... )
{
ISessionModel model = helper.ViewData.Model;
var sessionKey = model.SessionKey;
...
}
The only difference is that you don't have to do a cast....
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