ASP.NET MVC4中@model使用多個類型實例的方法


有時需要在ASP.NET MVC4的視圖的@model中使用多個類型的實例,.NET Framework 4.0版本引入的System.Tuple類可以輕松滿足這個需求。

public ActionResult Text2()
{
    Person person = new Person() { PersonId = 1, Name = "Tom" };
    Product product = new Product() { ProductId = 2, Name = "Jim" };
    Dictionary<int, string> dic = new Dictionary<int, string>();
    dic.Add(5,"AAA");
    return View(Tuple.Create(person, product,dic));
}

如下是視圖Index.cshtml的代碼:

@model Tuple<Demo1.Controllers.Person, Demo1.Controllers.Product, System.Collections.Generic.Dictionary<int,string>>
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Text2</title>
</head>
<body>
    <div>
        @Model.Item1.Name
        <br />
        @Model.Item2.Name
        <br />
        @foreach (var item in Model.Item3.Values)
        {
            <h5>@item</h5>
        }
    </div>
</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM