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
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With