MVC 从控制器跳转到视图的方法 |Model传值

1

跳转到视图的三种方法

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

namespace MvcApp.Controllers
{
    public class HomeController : Controller
    {
        
        // 一个业务逻辑可言适配多个客户端的视图展示

        public ActionResult Index()
        {
            //返回默认的视图
            return View();

            //返回同一个文件夹下的Add视图
            return View("Add");

            //返回不同文件夹下的TestAdd视图。(注意:这里需要写全视图的路径及后缀名)
            return View("/Views/Test/TestAdd.cshtml");
        }
        public ActionResult Add()
        {
            return View();
        }

    }
}


MVC用Model传值

传递对象

控制器

namespace MvcApp.Controllers
{
    public class HomeController : Controller
    {


        public ActionResult Index()
        {
            ViewData.Model = new Student() { Id = 1, Name = "小刚", Age = 25 };
            return View();          
        }
    }
}

视图(使用)

@{
    Layout = null;
}
@*注意:使用Model需要引入Model保存对象的类型*@
@model MvcApp.Models.Student 
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        <label>编号:</label> @Model.Id
        <label>姓名:</label> @Model.Name
        <label>年龄:</label> @Model.Age
        
    </div>
</body>
</html>


传递集合

控制器

namespace MvcApp.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            List<Student> list = new List<Student>{
                new Student { Id = 1, Name = "小刚", Age = 25 } ,
                new Student{ Id =2 , Name = "小明", Age = 26 } 
            };
            ViewData.Model = list;
            return View("Index1");
        }
    }
}

视图

@{
    Layout = null;
}
@model IEnumerable<MvcApp.Models.Student>

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index1</title>
</head>
<body>
    <div>
        @foreach (MvcApp.Models.Student s in Model)
        { 
            <label>编号:</label>@s.Id
            <label>姓名:</label>@s.Name
            <label>年龄:</label>@s.Age
        }
    </div>
</body>
</html>




  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值