close

最近遇到的問題,就是在一個View中使用多個Model的資料

這是其中之一個解法,使用dynamic的方式進行處理

這邊的範例是使用兩個table中的key值進行串連顯示

 

首先在Controller中進行建立

public ActionResult ContactDetail(int id = 0)
        {

            string pid = "";
            CustomerContact customercontact = db.CustomerContact.Find(id);      //找尋特定KEY值的資料列
            pid = customercontact.DetailKey;
            IEnumerable customerdetail = db.CustomerDetail.Where(c => c.Pid == pid).ToList();   //使用特定key找到另一張TABLE的資料表

            dynamic myModels = new ExpandoObject();      //建立dynamic物件
            myModels.customercontact = customercontact; //將customercontact放入
            myModels.customerdetail = customerdetail;   //將customerdetail放入

            return View(myModels);  //回傳

        }

 

 

View的接法

@using MvcApplication1.Models;  
@model dynamic 

@{
    ViewBag.Title = "ContactDetail";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>ContactDetail</h2>

<fieldset><legend>CustomerData</legend></fieldset>

<table>
	<tbody>
		<tr>
			<th>Id</th>
			<th>CNNAME</th>
			<th>EName</th>
		</tr>
		<tr>
			<td>@Model.customercontact.Id</td>
			<td>@Model.customercontact.CustomerCName</td>
			<td>@Model.customercontact.CustomerEName</td>
		</tr>
	</tbody>
</table>

<p>@foreach (CustomerDetail CustomerDetail in Model.customerdetail) { }</p>

<table>
arrow
arrow

    cs60811 發表在 痞客邦 留言(0) 人氣()