Ⅰ→通过ViewData传递数据,不过需要新建一个类(用来存)
NewClass(里面有表1的字段和表2的字段)
public class JoinTab1_2 { public int ID { get; set; } public string Name { get; set; } }
控制器中Action
public ActionResult Index() {using (DBEntities db = new DBEntities()) { var query = (from tab_1 in db.T_Tab1 join tab_2 in db.T_Tab2 on T_Tab1.TypeID equals T_Tab2.ID select new JoinTab1_2() { ID = tab_1.ID, Name = tab_2.Name }).ToList(); ViewData["query"] = query; return View(); } }
View中(可以直接在控制器中的Action直接右击→添加视图...然后类型选新建的这个,其它自定义吧)
<div class="table-responsive"> <table class="table" border="1"> <caption>测试</caption> <thead> <tr> <td> ID </td> <td> 类型名称 </td> <td> 操作 </td> </tr> </thead> <tbody>@foreach (var item in ViewData["query"] as IEnumerable<JoinInstrument>) { <tr> <td> @item.ID </td> <td> @item.Name </td> <td> <a class="btn" title="编辑" href="@Url.Action("GetInfo",new { id=@item.ID})">查看</a> <a class="btn" title="编辑" href="@Url.Action("Edit",new { id=@item.ID})">修改</a> <a class="btn" title="编辑" href="@Url.Action("Delete",new { id=@item.ID})">删除</a> </td> </tr> } </tbody> @*<tfoot> </tfoot>*@ </table> </div>
Ⅱ→通过return View(query);传递数据→会报错!!!
控制器中Action
public ActionResult Index() { using (DBEntities db = new DBEntities()) { var query = (from tab_1 in db.T_Tab1 join tab_2 in db.T_Tab2 on T_Tab1.TypeID equals T_Tab2.ID select new JoinTab1_2() { ID = tab_1.ID, Name = tab_2.Name }).ToList(); //ViewData["query"] = query; return View(query); } }
view中
<div class="table-responsive"> <table class="table" border="1"> <caption>测试</caption> <thead> <tr> <td> ID </td> <td> 类型名称 </td> <td> 操作 </td> </tr> </thead> <tbody>@foreach (var item in Model) { <tr> <td> @item.ID </td> <td> @item.Name </td> <td> <a class="btn" title="编辑" href="@Url.Action("GetInfo",new { id=@item.ID})">查看</a> <a class="btn" title="编辑" href="@Url.Action("Edit",new { id=@item.ID})">修改</a> <a class="btn" title="编辑" href="@Url.Action("Delete",new { id=@item.ID})">删除</a> </td> </tr> } </tbody> @*<tfoot> </tfoot>*@ </table> </div>
这样写会报错
我参考这篇文章也没搞出来
记dynamic的一个小坑 -- RuntimeBinderException:“object”未包含“xxx”的定义
大神看到希望能指点一二...
x
x