views:

185

answers:

1

I am working on my first ASP.NET MVC 2.0 app and realized that I am still confused about the best way to manage views.

For debugging, I would like to quickly dump data from several model classes into one view. I created a viewmodel class that combines the data into a single object.

   public class DBViewModel {

        public IQueryable<ClassAModel> class_a_list{ get; private set; }
        public IQueryable<ClassBModel> class_b_list { get; private set; }

        public DBViewModel(IRepository rep) {
            class_a_list = rep.FindAllClassA();
            class_b_list = rep.FindAllClassB();
        }
    }

Next I set up a controller action to populate the ViewModel Object and call the view.

 public ActionResult Foo() {
     [...]
     return View(new DBViewModel(rep));
 }

The question is now how to set up the View. I am ok to iterate over the objects for each model class but I would very much like to avoid manually listing all columns for each class. After all I am still in the early phase of fleshing out my model and I anticipate the schema to change frequently. It would be great if the View could handle those schema changes programatically and as I understand it, view templating is supposed to do exactly that.

Basically, what I am looking for is something along the lines of this (non-functioning) snippet:

<% foreach (var a in Model.class_a_list) { %>
   <p><%= Html.DisplayForModel(user) %></p>      
<% } %>

<% foreach (var b in Model.class_b_list) { %>
   <p><%: b.ToString() %></p>      
<% } %>

So, how should the view call the model data correctly?

Thanks!

A: 

Look at the top of your aspx file. You should see a line like:

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

Change it to:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewPage<MyNamespace.OtherNamespace.DBViewModel>" %>

(Obviously, substitute the correct namespaces.

Now your code below should "just work."

Craig Stuntz
I do inherit DBViewModel as you recommend. (Sorry for leaving the line out of my truncated example.) However, Html.DisplayForModel() is not generating any output. In a way, this doesn't surprise me since my model is a composition class with references to other model classes. What I really want is "Html.DisplayForModel(<obj from model.class_a>)". Unfortunately, DisplayForModel doesn't seem to provide functionality to specify which model/object to display.
duffy