多個Model(物件)
- 透過LINQ的Include方法與Lambda Expression將相關聯的資料(關聯資料表),由多個物件封裝成一個
- 範例:
Action:
public ActionResult ExInclude()
{
var courses = db.Courses
.Include(c=>c.Students)
.Include(c=>c.Schedule)
return View(courses.ToList());
}
View:
@model IEnumerable<Courses>
<!--標題-->
<tr>
<th>@Html.DisplayNameFor(model=>model.courseName)</th><th>@Html.DisplayNameFor(model=>model.Students.studentID)</th><th>@Html.DisplayNameFor(model=>model.Schedule.classTime)</th></tr>
<!--內容-->
@foreach(var item in Model){
<tr>
<td>@Html.DisplayFor(modelItem=>model.courseName)</td><td>@Html.DisplayFor(modelItem=>model.Students.studentID)</td><td>@Html.DisplayFor(modelItem=>model.Schedule.classTime)</td></tr>
}
ViewModel
- 專門給View使用的Model物件資料
- 可以將無相關聯的資料封裝成一個
- 將所需的多個物件透過一層Class進行屬性封裝
- 新增ViewModels目錄,通常放在Models目錄之下
- 範例:
Class:
public class Books
{
public string bookID {get;set;}
public string bookName {get;set;}
public IEnumerable<Order> Order {get;set;}
}
public class Order
{
public string orderNo {get;set;}
public string orderDate {get;set;}
public string orderNumber {get;set;}
}
Action:
public ActionResult ExViewModel()
{
List<Order> orders = new List<Order>();
orders.Add(new Order
{
orderNo="0001",
orderDate="2017-04-26",
orderNumber=2
});
orders.Add(new Order
{
orderNo="0002",
orderDate="2017-04-27",
orderNumber=3
});
Books books = new Books();
books.bookID = "A123456";
books.bookName = "MVC WOW";
books.Order = orders;
return View(books);
}
View:
@model Books
Book ID: @model.bookID
Book Name: @model.bookName
Order:
<table>
<tr>
<th>Order NO</th>
<th>Order Date</th>
<th>Order Number</th>
</tr>
@foreach(var item in model.Order)
{
<tr>
<td>item.orderNO</td>
<td>item.orderDate</td>
<td>item.orderNumber</td>
</tr>
}
</table>JSON
- 使用JavaScriptSerializer類別進行序列化工作,回傳時會設置ContentType為application/json
- 範例:
Model:
public class Person
{
public string id {get;set;}
public string name {get;set;}
public string email {get;set;}
}
Action:
public ActionResult ExJson()
{
Person person = new Person{ id="A001", name="isabella",email="a@b.c"};
return Json(person, JsonRequestBehavior,AllowGet);
}
沒有留言:
張貼留言