ASP.NET MVC教程四:ASP.NET MVC中页面传值的几种方式

准备

在Models文件夹里面新添加Student实体类,用来模拟从Controller向View传递数据,Student类定义如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCStudyDemo.Models
{
    public class Student
    {
        public int ID { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }

        public string Sex { get; set; }

        public string Email { get; set; }
    }
}

一、通过ViewData传值

MVC从开始版本就一直支持使用ViewData将Controller里面的数据传递到View。ViewData定义如下:

从上面的截图中可以看出,ViewData里面存的是字典类型的数据,在查看ViewDataDictionary的定义:

注意:ViewDataDictionary继承自IDictionary等接口,所以ViewData里面的Value值类型是object的,使用的时候需要进行类型转换。

新建Controller,并命名为ViewDataDemo,该Controller用来模拟通过ViewData向View传递数据

Controller代码如下:

using MVCStudyDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCStudyDemo.Controllers
{
    public class ViewDataDemoController : Controller
    {
        // GET: ViewDataDemo
        /// <summary>
        /// 通过ViewData向对应的View传递数据
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            // 1、将字符串传递到View
            ViewData["Other"] = "通过ViewData向View传递字符串";
            // 2、通过KeyValuePair添加
            ViewData.Add(new KeyValuePair<string, object>("name","tom"));
            // 3、直接添加
            ViewData.Add("age", 23);
            // 4、传递集合到View
            ViewData["Data"] = new List<Student>()
            {
                new Student
               {
                 ID = 1,
                 Name = "唐僧",
                 Age = 34,
                 Sex = "",
                 Email = "747976523@qq.com"
               },
               new Student
               {
                 ID = 2,
                 Name = "孙悟空",
                 Age = 635,
                 Sex = "",
                 Email = "sunwukong@163.com"
               },
               new Student
               {
                 ID = 3,
                 Name = "白骨精",
                 Age = 4532,
                 Sex = "",
                 Email = "74345523@qq.com"
               }
            };

            // 返回同名的视图
            return View();
        }
    }
}

 对应的View视图代码如下:

@*引入Student的命名空间*@
@using MVCStudyDemo.Models;
@{
    ViewBag.Title = "Index";
    // 这里使用的是Razor语法,写的是后台C#代码
    // ViewData的Value值是Object类型的,需要进行类型转换
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值