Wednesday, April 20, 2011

are strongly typed user control views not allowed asp.net mvc?

Here's the setup - I have a view that lists products. On that same page I have a user control view that lists categories.

I pass the list of product to the view like so:

return View(myProducts);

The user control view gets the data it needs via ViewData["Category"]

Now if I try to use a strongly typed user control view like this:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<myData.Models.Category>>" %>

I get this error:

The model item passed into the dictionary is of type 'System.Collections.Generic.List1[myData.Models.Product]' but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[myData.Models.Category]'.

The user control view seems to be confused since I am passing in a "Product" list to the view. So if I remove the strong typing like so:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>

Everything works fine.

So, are strongly typed user control views just not allowed? Or am I just doing something wrong?

From stackoverflow
  • A generic list of type A is not assignable to a generic list of type B (where B is derived from A). This is a general rule for all generic collections in .Net.

    tvanfosson : I think the problem is that he is using the same model for the partial view as for the page. According to the definitions, they should be different models entirely and I think he just needs to use a signature that allows him to pass the correct model into the partial.
  • When you render the partial view, use the ViewData["Category"] as the model that you pass to the control.

    <% Html.RenderPartial( "MyUserControl", ViewData["Category"], ViewData ); %>
    
    codette : Exactly what I was looking for, thanks!

0 comments:

Post a Comment