@model MvcApplication1.Models.M_Person @using MvcApplication1.Models; @{ ViewBag.Title = "GetData"; var p = ViewData["data"] as M_Person; var p2 = ViewBag.Data as M_Person; } <h2> GetData</h2> <div> 这是从ViewData.Model中取出的数据 @ViewData.Model.Name </div> <div> 这是从ViewData["data"]中取出的数据 @p.Age </div> <div> 这是从ViewBag.Data中取出的数据 @p2.Name @p2.Age </div> @{int i = 1;} @*@helper ChangeColor(int age) { if (age > 90) { <font color="red">@age</font> } else { @age } }*@ @*@functions{ public IHtmlString ChangeColor(int age) { if(age>90) { return new HtmlString("<font color='red'>"+age+"</font>"); }else { return new HtmlString(age + ""); } } }*@ <table border="1px" cellpadding="2px" cellspacing="0px" width="500px" style="border-collapse: collapse"> <tr> <th width="20px"> ID </th> <th> 和尚 </th> <th width="50px"> 年龄 </th> <th width="100px"> 操作 </th> </tr> @foreach (M_Person person in ViewBag.Persons) { <tr> <td align="center">@(i++) </td> <td align="center">@person.Name </td> @* <td align="center">@ChangeColor(person.Age)*@ @* <td align="center">@UIHelper.ChangeColor(person.Age)*@ @* <td align="center">@ChangeColor(person.Age)</td>*@ <td align="center">@UIFunctions.ChangeColor(person.Age)</td> <td align="center"> 删除||编辑 </td> </tr> } </table>
UIHelper.cshtml
@helper ChangeColor(int age) { if(age>90) { <font color="red">@age</font> }else { @age } }
UIFunctions.cshtml
@functions{ public static IHtmlString ChangeColor(int age) { if (age > 90) { return new HtmlString("<font color='red'>" + age + "</font>"); } else { return new HtmlString(age + ""); } } }
controller
public ActionResult GetData() { M_Person person = new M_Person() { Name = "济公活佛", Age = 90 }; ViewData["data"] = person; ViewData.Model = person; ViewBag.Data = person; List<M_Person> list = new List<M_Person>() { new Models.M_Person() { Name = "济公活佛", Age = 90 }, new Models.M_Person() { Name = "广亮和尚", Age = 88 }, new Models.M_Person() { Name = "怄气禅师", Age = 45 }, new Models.M_Person() { Name = "飞龙僧", Age = 123 } }; ViewBag.Persons = list; return View(); }