Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 4 pass model from view to html helper

I want to pass my ViewModel(not IEnumerable) to my custom html helper

I was doing on IEnumerable like this:

Helper:

public static IHtmlString GenerateTable<TModel, TValue>(this HtmlHelper<TModel> inHtml, IEnumerable<TValue> model)

View:

@Html.GenerateTable(Model)

But how i can pass model which is not IEnumerable to helper?

I Tried this:

public static MvcHtmlString MyHelper<TModel>(this HtmlHelper<TModel> html, object obj)
        {}

but when i call it like this

@Html.MyHelper(Model)

obj is always NULL

like image 930
Irakli Lekishvili Avatar asked Sep 23 '12 09:09

Irakli Lekishvili


2 Answers

Try like this:

public static MvcHtmlString MyHelper<TModel>(this HtmlHelper<TModel> htmlHelper)
{
    TModel model = htmlHelper.ViewData.Model;
    // TODO: do something with the model ...
}

and in your strongly typed view:

@model MyViewModel
@Html.MyHelper()
like image 127
Darin Dimitrov Avatar answered Nov 09 '22 18:11

Darin Dimitrov


I have tried your code and it works just fine, IF the Model has been initiatlised...... so I think you should check what @nemesv has suggested but I would clarify that the check should be done when you call the view and pass it the model...... there you need to check the model and make sure it is not null

like image 28
JTMon Avatar answered Nov 09 '22 18:11

JTMon