排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256
50010702506256
欢迎加群交流技术
分类:
Csharp
通过ViewData向前台传递字符串
ViewData["str"] = "666";
通过ViewBag向前台传递字符串
ViewBag.str = "666";
通过ViewData向前台传递数组
string[] str = {"香蕉","苹果","哈密瓜","西瓜","梨"};
ViewData["str"] = str;
//或者 ViewBag.strlist = str;通过ViewData向前台传递对象
//对象部分
public class Users
{
public string UserName { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
//对象集合数据表
List<Users> list = new List<Users>(){
new Users() { UserName = "刘备", Age = 54, Address = "蜀" },
new Users() { UserName = "刘邦", Age = 53, Address = "楚" },
new Users() { UserName = "关羽", Age = 52, Address = "蜀" },
new Users() { UserName = "曹操", Age = 54, Address = "魏" },
new Users() { UserName = "张飞", Age = 50, Address = "蜀" },
new Users() { UserName = "马超", Age = 44, Address = "西凉" },
new Users() { UserName = "李白", Age = 33, Address = "唐" }
};
//通过ViewData向前台传递对象集合
ViewData["Userslist"] = list;前台获取
@* 使用对象先引用对象的类 或者写上对象的全名 *@
@using MvcApplication1.Models;
@{
//将后台传的值强转成同类型
List<Users> list = ViewData["Userslist"] as List<Users>;
}
@*循环输出生成数据表*@
<table>
@{
foreach (Users item in list )
{
<tr>
<td>@item.UserName</td>
<td>@item.Age</td>
<td>@item.Address</td>
<br/>
</tr>
}
}
</table>通过Modle传值
//数据表同上 //通过Models传值到前台 return View(list);
前台部分
@*通过model从前台接收值,并且指定类型(指定类型时model为小写),可以不指定类型*@
@model List<Users>
<table>
@{
foreach (Users item in Model)
{
<tr>
<td>@item.UserName</td>
<td>@item.Age</td>
<td>@item.Address</td>
<br/>
</tr>
}
}
</table>总结
MVC 传递参数的方法一共有三种
ViewData 使用方法 ViewData["str"] = "字符串";
ViewBag 使用方法 ViewBag.str = "字符串"
(用法与ViewData十分类似,只是写法上有一点点区别,甚至可以ViewData定义,ViewBag接收)
Modle 使用方法
后台 return View(list);
前台 直接Modle (可指定类型,也可以不指定类型)
@*通过model从前台接收值,并且指定类型(指定类型时model为小写)*@
@model string
评价