MVC,控制器向视图传递数据的方式:
control
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UI.Models;
namespace UI.Controllers
{public class StudentController : Controller{//// GET: /Student/public ActionResult ABC(){string msg = "这是控制器传递给视图的数据.....";ViewData[ "msg" ] = msg;Student s1 = new Student { Id = 100 , Name = "东方不败" };ViewData[ "student" ] = s1;List<Student> lst = new List<Student>( ){new Student{Id=101,Name="张无忌"},new Student{Id=102,Name="张翠山"},new Student{Id=103,Name="张三丰"},new Student{Id=104,Name="张松溪"}};ViewData[ "list" ] = lst;return View();}}
}
view
@using UI.Models;<!DOCTYPE html><html>
<head><meta name="viewport" content="width=device-width" /><title>ABC</title>
</head>
<body><div>@{Student s1 = ViewData[ "student" ] as Student;}<h1>学生管理平台</h1><h2>@ViewData["msg"].ToString()</h2><h3>学生姓名:@s1.Name</h3><div><ul>@{List<Student> lst = ViewData["list"] as List<Student>;foreach ( var std in lst){<li>@std.Name</li>}}</ul></div></div>
</body>
</html>
control
public ActionResult ViewBagDemo( ){string sql = "select * from book";DataTable dt = DBHelper.Query( sql , null , false );List<Book> books = new List<Book>( );foreach ( DataRow row in dt.Rows ){Book bk = new Book{BID = Convert.ToInt32( row[ "bid" ] ) ,BName = row[ "bname" ].ToString( ) ,BCount = Convert.ToInt32( row[ "bcount" ] )};books.Add( bk );}ViewBag.books = books;return View( );}
view`
@using UI.Models;<!DOCTYPE html><html>
<head><meta name="viewport" content="width=device-width" /><title>ViewBagDemo</title><style type="text/css">.tab {width:50%;border:solid 1px blue;border-collapse:collapse;}.tab td{text-align:center;border:solid 1px blue;}</style>
</head>
<body><h1>ViewBag案例</h1><div><table class="tab"><tr><td>书号</td><td>标题</td><td>库存</td></tr>@{foreach ( var bk in ViewBag.books ){<tr><td>@bk.BID</td><td>@bk.BName</td><td>@bk.BCount</td></tr>}}</table></div>
</body>
</html>
control
public ActionResult TempDate( ){TempData[ "book" ] = new Book{BID = 100 ,BName = "雪山飞狐" ,BCount = 10};//跳转到指定的Action中return RedirectToAction( "AccepTempData" );}public ActionResult AccepTempData( ){Book bk = TempData[ "book" ] as Book;ViewBag.book = bk;return View( );}}
view
@using UI.Models;<!DOCTYPE html><html>
<head><meta name="viewport" content="width=device-width" /><title>Index</title>
</head>
<body><div><a href="/Student/ABC">ViewData传递数据</a></div><div><a href="/Book/BookList">图书列表(ViewData)</a></div><div><a href="/Book/ViewBagDemo">图书列表(ViewBag)</a></div><div><a href="/Book/TempDate">TempData案例</a></div><div>@{if ( ViewData["books"] !=null ){List<Book> books = ViewData[ "books" ] as List<Book>;foreach ( var bk in books ){<div>@bk.BName</div>}}}</div>
</body>
</html>
找到 Student (Control) ABC(action)
本文发布于:2024-01-30 18:54:18,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170661206022118.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |