分三种:ViewBag,ViewData,View()+Model
一、ViewBag
ViewBag时,前端接收不需要转类型
后台代码
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
List<string> colors = new List<string>();
colors.Add("Red");
colors.Add("blue");
ViewBag.Listcolors = colors;
return View();
}
view
@{
ViewBag.Title = "About";
}
<script>
var message='@Html.Raw(ViewBag.Message)';
</script>
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<p>Use this area to provide additional information.</p>
<ul>
@foreach (var color in ViewBag.ListColors)
{
<li>@color</li>
}
</ul>
二、ViewData
需要转类型 后台
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
List<string> colors = new List<string>();
colors.Add("Red");
colors.Add("blue");
ViewData["ListColors"] = colors;
ViewData["DatetimeNow"] = DateTime.Now;
return View();
}
View
@{
ViewBag.Title = "About";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<p>Use this area to provide additional information.</p>
<ul>
@foreach (var color in ViewData["listColors"] as List<string>)
{
<li>@color</li>
}
</ul>
<p>@ViewData["DatetimeNow"]</p>
三、View()+Model
需要Model 后台 Model
namespace TestSpace.Models
{
public class Dog
{
public string Name{set; get;}
public int Age{set; get;}
}
}
控制器
public ActionResult ShowList()
{
List<Dog> list=new List<Dog>();
list.Add(dogs);
return View(list);
}
View
@model System.Collections.Generic.List<TestSpace.Models.Dog>
...
...
...
<p>@Model[0].Name</p>
|