6

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

3
  • 1
    Have you checked that your Model is not null when calling @Html.MyHelper(Model)? Commented Sep 23, 2012 at 9:54
  • It is create view model its does have values but i want to access models properties names and metadatas Commented Sep 23, 2012 at 9:55
  • I have tried your code and it works just fine, IF the Model has been initiated...... so I think you should check what @nemesv has suggested Commented Sep 23, 2012 at 10:36

2 Answers 2

11

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()
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.