1. 程式人生 > >Asp.net Mvc action返回多個模型實體給view

Asp.net Mvc action返回多個模型實體給view

姓名 query ont info erb users box html asp

1、controller中action代碼:

public class HomeController : Controller
    {
        public ActionResult Detail(int id)
        {
            UserInfo master = masterBLL.QueryOne(x => x.StudentID == id);//主表
            UserSlave slave = slaveBLL.QueryOne(x => x.StudentID == id);//從表
            return View(Tuple.Create(master, slave));
        }
    }

Tuple是c#4.0的新特性。

如果返回三個,則 Tuple.Create(master, slave1 , slave2)

2、view代碼:

@{
    Layout = null;
}
@model Tuple<Model.UserInfo, Model.UserSlave>
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta name=viewport content=width=device-width,initial-scale=1.0
> </head> <body> <table> <tr> <td><span>姓名</span></td> <td> @Html.DisplayFor(model => model.Item1.Name) </td> </tr> <tr> <td><span>郵箱</span></td> <td> @Html.DisplayFor(model
=> model.Item2.Email) </td> </tr> </table> </body> </html>

model.Item1表示實體模型UserInfo,model.Item2表示實體模型UserSlave

如果是textbox控件,寫法一樣:

@Html.TextBoxFor(model => model.Item1.Name, new { placeholder = "姓名", maxlength = "20" })

Asp.net Mvc action返回多個模型實體給view