如何将Controller 中的数据传送到View
步骤:
(1)要有数据,如果要用到对象可以在Model 中定义对应的类
(2)要有装数据的容器: System.Text.StringBuilder sbHtml = new System.Text.StringBuilder(4000);
(3)要将数据放入容器: sbHtml.AppendLine("<div>"+d.ToString()+"</div>");
(4)要将容器传递给视图: ViewBag.HtmlStr = sbHtml.ToString();
(5)视图接收数据并做相应处理: @Html.Raw(ViewBag.HtmlStr)
代码
<<Model>>
namespace Test_Mvc.Models
{
public class Dog
{
public int ID { get; set;}
public string Name { get; set; }
public override string ToString()
{
return "ID = "+this.ID + "Name = "+ this.Name;
}
}
}
<<Controller>>
List<Models.Dog> list = null;
//初始化数据集合
public List<Models.Dog> InitData()
{
list = new List<Models.Dog>()
{
new Dog(){ID = 1,Name="小样"},
new Dog(){ID = 1,Name="小样"},
new Dog(){ID = 1,Name="小样"},
new Dog(){ID = 1,Name="小样"}
};
return list;
}
public ActionResult Index2()
{
System.Text.StringBuilder sbHtml = new System.Text.StringBuilder(4000);
// ViewBag.Message = "修改此模板以快速启动你的 ASP.NET MVC 应用程序。";
List<Models.Dog> list = InitData();
list.ForEach(d =>
{
sbHtml.AppendLine("<div>" + d.ToString() + "</div>");
});
ViewBag.HtmlStr = sbHtml.ToString();
return View();
}
<<View>>
<body>
<!--相当于吧 action 中保存的数据输出 !-->
@Html.Raw(ViewBag.HtmlStr)
</body>