Get Model associated with corresponding View in HtmlHelper

10,619

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....

Share:
10,619
Robin Maben
Author by

Robin Maben

LinkedIn Profile Github Profile Other Thoughts

Updated on June 15, 2022

Comments

  • Robin Maben
    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 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.

  • Red Taz
    Red Taz over 8 years
    Surely this doesn't compile, you're implicitly casting object to ISessionModel?