开发者

How do I obtain an HtmlHelper<TModel> instance for a model in ASP.NET MVC?

开发者 https://www.devze.com 2022-12-25 14:38 出处:网络
Let\'s say I have an Index view. The model I pass in is actually a collection of models, so the Html property is of type HtmlHelper<List<MyModel>>. If I want to call extension methods (e.g

Let's say I have an Index view. The model I pass in is actually a collection of models, so the Html property is of type HtmlHelper<List<MyModel>>. If I want to call extension methods (e.g., Display() or DisplayFor() on the individual items in the list, however, I think I need to obtain an HtmlHelper<MyModel>. But how?

I tried using the HtmlHelper<TModel> constructor, which looks like this:

HtmlHelper<TModel>(ViewContext, IViewDataContainer)

But I'm not having any luck with that. I don't know how to obtain the IViewDataContainer for the it开发者_如何学Cem, and the documentation on these things is very sparse.

A lot of magic apparently happens when I do...

return View(List<MyModel>);

...in my controller.

How do I recreate that magic on individual items in a list/collection?

Update

Here is a code snippet to show what I'm trying to accomplish:

        foreach(var item in items)
        {
            var helper = new HtmlHelper<ProjName.MyModel>(ViewContext, ????);
%>
            <tr>
<%
                foreach(var property in properties)
                {
%>
                    <td>
                        <%=  helper.Display(property.DisplayName) %>
                    </td>
<%          
                }
%>
            </tr>
<%
        }

Basically, I want to populate the cells of a table using the items in the collection. I just need help setting the helper variable.


One idea is to use RenderPartial. So create a user control which has the type of your model (MyModel). Then in your main view, add the following code.

<% Html.RenderPartial("SubView", property); %>

So the main view would look like:

 foreach(var item in items) 
 { 
    %> 
    <tr> 
    <% 
        foreach(var property in properties) 
        { 
         %> 
            <td> 
                <%= Html.RenderPartial("SubView", property) %> 
            </td> 
        <%           
        } 
        %> 
    </tr> 
    <% 
    }
    %>

Then the sub view would be a strongly typed user control of type . The sub view can then just call the helper and it will be of the correct type:

<%= Html.Display(Model.DisplayName) %>


Phil Haack to the rescue!

http://haacked.com/archive/2010/05/05/asp-net-mvc-tabular-display-template.aspx


The page itself is a IViewDataContainer. You could try that :

foreach(MyModel m in Model)
{
    HtmlHelper helper = new HtmlHelper<MyModel>(ViewContext, this);
    ...
}

UPDATE

Another idea : you could create a ViewUserControl<MyModel> and use RenderPartial to render each item with this control. ViewUserControl<MyModel> exposes a HtmlHelper<MyModel> that you can use to render the model

0

精彩评论

暂无评论...
验证码 换一张
取 消