Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Model object in a custom Html helper

Tags:

asp.net-mvc

I'm trying to create a custom HTML helper and I would like to know how I can access the Model object without passing it as a parameter.

Thanks

like image 644
burnt1ce Avatar asked Nov 15 '10 16:11

burnt1ce


1 Answers

If you are using strongly typed views which you should:

public static MvcHtmlString MyHelper<TModel>(this HtmlHelper<TModel> htmlHelper)
{
    TModel model = htmlHelper.ViewData.Model;
    return MvcHtmlString.Empty;
}

If you are not using strongly typed views which you shouldn't:

public static MvcHtmlString MyHelper(this HtmlHelper htmlHelper)
{
    object model = htmlHelper.ViewData.Model;
    return MvcHtmlString.Empty;
}
like image 156
Darin Dimitrov Avatar answered Nov 02 '22 22:11

Darin Dimitrov