ASP.NET MVC页面传值

1、Viewbag

//后端
 base.ViewBag.user1 = "张三";

//页面取值
@ViewBag.user1

2、ViewData

//后端
   base.ViewData["user2"] = "李四";
//页面取值 
  @.ViewData["user2"]

3、session

//后端
 base. HttpContext.Session["usr3"] = "王五";
 
 //页面取值
 @HttpContext.Current.Session["usr3"]

4、TempData

//后端
    base.TempData["user4"] = "王六";
    
//页面取值e
 @TempData["user4"]

5、传对象( ViewData.Model)

//后端
 student stu = new student(12, "789");  //student是一个对象
 ViewData.Model= stu;
 
//页面取值
@model mvc.Models.student  //首先页面数据绑定

<h3>@ViewData.Model.name</h3> 
**注意:页面强类型,操作的成员变量必须被public修饰,否则不行**

6、传集合

//后端
List<Person> list1 = new List<Person>()
            {
                new Person {name="weijuan",age=26 },
                new Person { name="bingbing",age=27},
                new Person { name="tutu",age=10}
            };

            ViewData.Model = list1;

//页面取值
@model List<WebApplication2.Models.Person>//数据绑定
<table class="table table-bordered table-hover">  //class属性表示表格的样式
    <thead>
        <tr>
            <th>姓名</th>
            <th>年龄</th>
        </tr>

    </thead>

    <tbody>  
            @foreach (var item in Modedl) {
                <tr>
                <td>@item.name</td>
                <td>@item.age</td>
                </tr>
            }
    </tbody>

</table>

在这里插入图片描述
7、区别:当使用(Redirect)重定向的时候,ViewBage、ViewData 、ViewData.Model的值会发生丢失,
base. HttpContext.Session、 base.TempData的值不会发生丢失

//Index的后端
public ActionResult Index()
        {
            base.ViewBag.user1 = "张三";
            base.ViewData["user2"] = "李四";
            base. HttpContext.Session["usr3"] = "王五";
            base.TempData["user4"] = "王六";
            string name = "王七";
            ViewData.Model = name;

            return Redirect("/home/ToIndex");           
        }




//ToIndex的后端

  public ActionResult ToIndex() {
            return View();
        }
        
//ToIndex的前端

<h1>@ViewBag.user1</h1>
<h1>@ViewData["user2"]</h1>
<h1>@HttpContext.Current.Session["usr3"]</h1>
<h1>@TempData["user4"]</h1>
<h1>@ViewData.Model</h1>


//只会显示

王五
王六
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值