AspNet MVC4 教学-22:Asp.Net MVC4 Partial View 技术高速应用Demo
A.创建Basic类型的MVC项目.
B.Model文件夹下,创建文件:
LoginModel.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MvcPartialViewTest.Models { public class LoginModel { public string Name { get { return "张三"; } } public string Remark { get { return "航大学生."; } } public double Score { get { return 99.12; } } } }
OtherModel.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MvcPartialViewTest.Models { public class OtherModel { public string Name { get { return "李四"; } } public string Remark { get { return "航小学生."; } } public double Score { get { return 100; } } } }
C.创建HomeController.cs文件:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcPartialViewTest.Models; namespace MvcPartialViewTest.Controllers { public class HomeController : Controller { // GET: /Home/ public ActionResult Index() { ViewData.Model = new LoginModel(); return View(); } public ActionResult GetPartialView() { return PartialView("PartialLink"); } public ActionResult GetPartialView2() { return PartialView("PartialDataFromOtherModel", new OtherModel()); } } }
C.创建对应的PartialView:
1)PartialLink.cs:
<a href="http://www.sina.com.cn">新浪</a> <a href="http://www.sohu.com">搜狐</a> <a href="http://www.exesoft.cn">行易软件</a>2)PartialDataFromLoginModel.cshtml:
@using MvcPartialViewTest.Models @model LoginModel <h2>@Model.Name</h2> <h2>@Model.Remark</h2>
3)PartialDataFromView.cshtml:
@model System.Double <h2>@Model</h2>
4)PartialDataFromOtherModel.cshtml:
@model MvcPartialViewTest.Models.OtherModel <fieldset> <legend>OtherModel</legend> <div class="display-label"> @Html.DisplayNameFor(model => model.Name) </div> <div class="display-field"> @Html.DisplayFor(model => model.Name) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.Remark) </div> <div class="display-field"> @Html.DisplayFor(model => model.Remark) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.Score) </div> <div class="display-field"> @Html.DisplayFor(model => model.Score) </div> </fieldset>
D.创建View文件:
Index.cshtml:
@using MvcPartialViewTest.Models @model LoginModel @{ ViewBag.Title = "Index"; } <h2>1.没有參数传递的PartialView</h2> <h2>@Html.Partial("PartialLink")</h2> <hr /> <h2>2.直接从LoginModel中获取数据的PartialView</h2> @Html.Partial("PartialDataFromLoginModel") <hr /> <h2>3.从View中间接获取LoginModel数据的PartialView</h2> @Html.Partial("PartialDataFromView", Model.Score) <hr /> <h2>4.从控制器直接加载分布视图,不再套用主版视图</h2> <h2>@Html.ActionLink("取得PartView","GetPartialView")</h2> <hr /> <h2>5.结合上面创建的的Action,使用Html.Action再次加载</h2> <h2>@Html.Action("GetPartialView")</h2> <hr /> <h2>6.使用Html.Action,通过Action获取OtherMode数据的PartialView</h2> <h2>@Html.Action("GetPartialView2")</h2>E.效果图: