-----------------------------------
使用动态特性ViewBag,它主要是为了从控制器到视图进行传值用的
//----控制器方法 public ActionResult Sample() { //动态属性 ViewBag.Name = "你好!张迪"; //返回视图的名称(对应着Views-->Store-->Sample2.cshtml) return View("Sample2"); //return View("~\Views\Store\Sample2.cshtml"); } //----视图 @{ ViewBag.Title = "Sample"; } <h2>Sample</h2> <!--获取控制器中设置的属性--> <h2>@ViewBag.Name</h2>
-----------------------------------从控制器到视图传递泛型(1)
//----控制器 public ActionResult Array() { List<string> list = new List<string>(); for (int i = 0; i < 10; i++) { list.Add(i.ToString()); } ViewBag.Array = list; return View(); } //----视图 @{ ViewBag.Title = "Array"; } <h2>Array</h2> @foreach (string item in (List<string>)ViewBag.Array) { <li>@item</li> }
-----------------------------------从控制器到视图传递泛型(2)
//----控制器 public ActionResult Array() { List<string> list = new List<string>(); for (int i = 0; i < 10; i++) { list.Add(i.ToString()); } ViewBag.Array = list; return View(); } //----视图 @{ ViewBag.Title = "Array"; } <h2>Array</h2> @foreach (dynamic item in ViewBag.Array) { <li>@item</li><!--如果有属性,则需要硬写上--> }
时间: 2024-11-09 04:06:28