views:

18

answers:

1

I am trying to pass a strongly typed object to a UserControl, but I am not able. I must be missing something. So my User Control expects an object of type Data which contains a list of string. On my page, I call RenderPartial with the name of my user control and the data. However, when the page run, it says in that this.Model (or this.ViewData.Model) is null. Why? What am I missing?

Page.aspx

<% Html.RenderPartial("UserControl", ViewData["Data"]); %>

PageController.cs

ViewData["Data"] = new Data() 
{ 
    Links = new List<Link> 
    { 
    } 
};

Data.cs

public class Data
{
    public List<string> Links { get; set; }
}

UserControl.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Proto.Models.Data>" %> 
    <% 
        foreach (var link in this.Model.Links)
        { 
           // ...
        }
    %>
+1  A: 

ViewData just contains a mapping of string -> object. You need to cast it to the type that your strong-typed view is expecting:

<% Html.RenderPartial("UserControl", (Data) ViewData["Data"]); %>

Personally, I would suggest that you make everything strong-typed, and eschew the use of ViewData entirely, but I understand that's not always possible :)

Dean Harding