Get Model associated with corresponding View in HtmlHelper
Solution 1
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;
...
}
Solution 2
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....
Comments
-
Robin Maben almost 2 years
My View inherits
Models.MyModel
<%@ Page Language="C#" MasterPageFile="Something.Master" Inherits="Models.MyModel>" %>
I need a property
Model.Something
to be available in aHtmlHelper
method when I call it from this view.<%= Html.CustomHelper(...) %>
Is there any way to access this? Maybe via
ViewContext
orViewDataDictionary
?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.
-
Red Taz over 8 yearsSurely this doesn't compile, you're implicitly casting
object
toISessionModel
?