ASP.NET MVC 第三回 Controller与View

时间:2022-12-10 23:53:28
这节我们让ASP.NET MVC真正的跑起来

一、新建Controller

首先我们自己新建一个新的Controller在Controllers上点右键,添加,Controller选项
ASP.NET MVC 第三回 Controller与View  
之后出现一个对话框:
ASP.NET MVC 第三回 Controller与View  
这里我们将之起名为EiceController 
默认生成的代码如下:
    //记不记得前面讲过的,所有Controller都要继承于Controller类
public class EiceController : Controller
{
public ActionResult Index()
{
return View();
}
}

二、新建View文件

当然,除了Controller我们还要建个View,先在Views中建个Eice文件夹,然后我们要在其中建个Index.aspx。
不过除此之外ASP.NET MVC还为我们提供了一种新建View的快捷方式。
在对应的Controller的Action中点右键,选择Add View。
ASP.NET MVC 第三回 Controller与View 
之后弹出窗口
ASP.NET MVC 第三回 Controller与View
确定好View文件名字及母版文件后点Add就建好了一个View文件。
<%@ 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>
如果要建无母版页面勾去select master page即可。

三、编辑Controller、View完成一个简单的页面传值

我们将EiceController的Index改写为
    public class EiceController : Controller
{
public ActionResult Index(string id)
{
ViewData["chsword"] = id;
return View();
}
}
在View文件即/Views/Eice/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>
下面我们来访问/Eice/Index/HellowEice,可以看到:
ASP.NET MVC 第三回 Controller与View
这样我们就将一个值从Url传到Controller,又从Controller传到View显示出来。
由上面程序段可以看出Action的参数string id用于接收{Controller}/{Action}/{id}的ID部分
ViewData是一个页面间的IDictionary用于Controller向View传递数据 
这样View与Controller就可以协作完成显示页面与逻辑处理的工作了
 
那除了ViewData之外我们还有什么方法由Controller向View文件传值?我们除了能显示aspx文件外还能显示其它的文件么?