accessing viewmodel data in MVC2.0 view
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!
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."
精彩评论