本章节主要介绍如何利用ASP.NET MVC编写自己想要的页面。具体过程如下所示(由于目前CSDN禁止上传图片,所以只能去网上拷贝该部分,所有代码测试通过,请大家放心使用)。
鼠标右击解决方案下的Controllers文件夹->选择添加->选择Controller选项,如下图所示:
然后会出现一个对话框,如下图所示:
我们可以任意取名,在此我们取名RocketController。
则在Controller文件夹下面多了个文件为RocketController.cs,默认生成的代码为:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; namespace MovieApp.Controllers { public class RocketController : Controller { // // GET: /Rocket/ public ActionResult Index() { return View(); } } }
当然,除了Controller我们还要建个View,先在Views中建个Rocket文件夹,然后我们要在其中建个Index.aspx。
不过除此之外ASP.NET MVC还为我们提供了一种新建View的快捷方式。在对应的Controller的Action中点右键,选择Add View。本文采用后者。具体如下图所示:
之后弹出一个对话框,如下图所示:
确定好View文件名字及母版文件后点Add就建好了一个View文件。Index.aspx的默认代码为:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Index </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Index</h2> </asp:Content>
我们将RocketController.cs的代码修改为:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; namespace MovieApp.Controllers { public class RocketController : Controller { // // GET: /Rocket/ public ActionResult Index(string id) { ViewData["chsword"] = id; return View(); } } }
而Views/Rocket/Index.aspx的代码修改为:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Index </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <%=ViewData["chsword"]%> </asp:Content>
下面我们来访问/Rocket/Index/HellowEice,可以看到如下页面:
这样我们就将一个值从Url传到Controller,又从Controller传到View显示出来。由上面程序段可以看出Action的参数string id用于接收{Controller}/{Action}/{id}的ID部分。ViewData是一个页面间的IDictionary用于Controller向View传递数据。这样View与Controller就可以协作完成显示页面与逻辑处理的工作了。