views:

51

answers:

3

My action creates a strongly typed viewdata, which is passed to my view.

In the view, I pass the Model to the render partial method.

public ActionResult Index()
{
            ViewDataForIndex vd = new ViewDataForIndex();

            vd.Users = Users.GetAll();

            return View(vd);
}


public class ViewDataForIndex: ViewData
    {
          public IList<User> Users {get;set;}

    }

now in the view:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ViewDataForIndex>" %>

<% Html.RenderPartial("~/controls/blah.ascx", ViewData.Model); %>

and in blah.ascx:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
  1. how do I access my model now?
  2. if I wanted to create a strongly typed class for my ViewUserControl, how would I do that? inherit from?
A: 

One: Inside the ascx:

   <%= Model.YourProperty %>

Two: Provide a type Argument to ViewUserControl:

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

I like @jfar's second approach better as it allows for easier modification if you ever decide to pass a more complex model to the view.

So you may pass a class that has multiple properties and/or more child objects.

If you inherit from the object now, then all you need to do is to inherit from your complex object and change one piece of code, as well as add the new properties, and your done.

griegs
A: 

More specifically to jfar's answer:

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

If your parent page has a model of type ViewDataForIndex, calling the child with the same ViewData.Model will also pass an object of type ViewDataForIndex.

Jarrett Meyer
Heh, I must have had a cached answer when you edited mine.
jfar