The.Professor
The.Professor

Reputation: 21

new HTMLHelper with generic type

So I tried searching, but I'm not exactly sure what to search for. I'm trying to make an HtmlHelper extension that takes a model that is of type MyModel. However, the View takes a model type List(Of MyModel). In my extension, which was originally created to take just MyModel, when the View Model is a List(of MyModel) and I use

For Each Item in Model
    Html.MyHelper(Item)
Next

I get an exception 'The model item passed into the dictionary is of type 'System.Collections.Generic.List1[MyModel]'`, but this dictionary requires a model item of type 'MyModel'.'

My original Helper is

Public Function FormatTable(Of T As Class)(helper As HtmlHelper, model As T) as OutModel(Of T)

and i want something like

Public Function FormatTable(Of List(of T As Class))(helper As HtmlHelper, model As T, 
       tableType As RenderType, Optional columns As Integer = 2) As FormatTable(Of T)

or should i create a new helper in the view to pass?

Upvotes: 0

Views: 1322

Answers (1)

The.Professor
The.Professor

Reputation: 21

Although I'm not sure how to do a Function MyExtension(of List(Of T as Class))(model as T) or if that's even possible, I did solve my situation. I needed to create an HtmlHelper of a different class type and use a different model and found MvcUtil which does just that.

I came across this post: Stronglytyped html helper with different model for get and post

In my view i create a new htmlhelper of the new model type to call my htmlextension

For Each Item in Model
    @Html.HtmlHelperFor(Of MyType)().MyExtension(Item)
Next

and now have a check

If(IsNothing(helper.ViewData.Model)) Then
    helper = helper.HtmlHelperFor(Of T)(model)
End If

This solved my problem when looping through a list in my View.

Upvotes: 1

Related Questions