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>