分类:
NET
MVC后台向前台传值:
l Viewdata
Viewdata[key] = xj
l Viewbag
Viewbag.key = xj
l model
model传参一次只能传一个
model传参的类型转化更简单一点,
@model 接类型即可
ltempdata
用法和viewdata类似,TempData["name"] = value。只是他是一个临时变量,一次请求中有效,第二次就失效了
Viewdata,Viewbag其实都是一个键值对,三种传参的方式其实显示几乎都是一样的,字符串,int这些可以直接显示。如果是对象类型做一个转化在显示即可
一个action多钟传参可以一起使用
简单案例:
后台:
public ActionResult Index() { //传一个简单的字符串 ViewData["name"] = "hello razor22222"; List<string> fruits = new List<string>() { "西瓜", "苹果", "桃子", "李子" }; ViewData["fruits"] = fruits; UserInfo userInfo = new UserInfo() { Id = 1, UserName = "诸葛詹", Age = 19, Area = "蜀国" }; ViewData["userInfo"] = userInfo; List<UserInfo> userInfos = new List<UserInfo>() { new UserInfo(){ Id=1, UserName="诸葛亮",Age=27, Area="蜀国" }, new UserInfo(){ Id=2, UserName="诸葛亮",Age=30, Area="蜀国" }, new UserInfo(){ Id=3, UserName="曹操",Age=30, Area="魏国" }, new UserInfo(){ Id=4, UserName="孙权",Age=25, Area="吴国" }, new UserInfo(){ Id=5, UserName="黄月英",Age=20, Area="蜀国" }, new UserInfo(){ Id=6, UserName="黄忠",Age=70, Area="蜀国" }, new UserInfo(){ Id=7, UserName="孙尚香",Age=18, Area="吴国" }, new UserInfo(){ Id=2, UserName="诸诸侠",Age=27, Area="吴国" }, }; ViewData["userInfos"] = userInfos; return View(); }
前台:
<div style="margin-top:20px"> @ViewData["name"] </div> <div style="margin-top:20px"> @{ List<string> friuts = ViewData["fruits"] as List<string>; WebApplication2.Models.UserInfo userInfo = ViewData["userInfo"] as WebApplication2.Models.UserInfo; List<WebApplication2.Models.UserInfo> userInfoList = ViewData["userInfos"] as List<WebApplication2.Models.UserInfo>; } @foreach (var item in friuts) { <div>@item</div> } </div> <div style="margin-top:20px"> <div> 姓名:<span>@userInfo.UserName</span>,年龄:<span>@userInfo.Age</span>,国家:<span>@userInfo.Area</span> </div> </div> <div style="margin-top:20px"> @foreach (var item in userInfoList) { <div> 姓名:<span>@item.UserName</span>,年龄:<span>@item.Age</span>,国家:<span>@item.Area</span> </div> } </div>
评价
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术