Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Model associated with corresponding View in HtmlHelper

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.

like image 267
Robin Maben Avatar asked Nov 24 '10 13:11

Robin Maben


People also ask

How do I access my razor view model?

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.

Which HtmlHelper object method should you use?

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.

What does return View () in MVC do?

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.


2 Answers

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;

    ...
}
like image 75
tvanfosson Avatar answered Oct 12 '22 08:10

tvanfosson


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

like image 26
devlife Avatar answered Oct 12 '22 07:10

devlife