开发者

How to strongly type a view with 2 classes?

Is it possible 开发者_运维百科to strongly type a view with 2 tables? I mean if I want to display a view that contains data coming from 2 tables and then how do I stongly type a view with my data that comes from 2 tables?


You can't do that directly but you can create a ViewModel class with two properties on it that hold references to your table. You strongly type the View against that ViewModel class.

ViewModel:

public class ViewModelTables
{
   public MyTable customer {get; set;}
   public MyOtherTable MyOtherTable {get; set;}
}

View:

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

<% foreach(var tab1Item in Model.customer)
   { %>
   // render here what ever you want to render
   <%: Html.TextboxFor(name => tab1Item.Name) %>
<% } %>

<% foreach(var tab2Item in Model.MyOtherTable)
   { %>
   // render here what ever you want to render
<% } %>

Controller:

public ActionResult MyDoubleTables()
{
   var my2Tab = new ViewModelTables();

   var tab1 = GetTable1(); // whatever you need to do 
   var tab2 = GetTable2(); // whatever you need to do 

   my2Tab.MyTable = tab1;
   my2Tab.MyOtherTable = tab2;

   return View(my2tab);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜