ASP.NET MVC 重点教程一周年版 第三回 Controller与View

这节我们让ASP.NET MVC真正的跑起来

一、新建Controller

首先我们自己新建一个新的Controller在Controllers上点右键,添加,Controller选项

image 
之后出现一个对话框:

image 
这里我们将之起名为EiceController
附注一下,这里是个纯广告,无兴趣可略过此行:www.eice.com.cn为您建立Web2.0社交网站
默认生成的代码如下:

    //记不记得前面讲过的,所有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。

image 

之后弹出窗口

image

确定好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,可以看到:

image

这样我们就将一个值从Url传到Controller,又从Controller传到View显示出来。

由上面程序段可以看出Action的参数string id用于接收{Controller}/{Action}/{id}的ID部分

ViewData是一个页面间的IDictionary用于Controller向View传递数据
这样View与Controller就可以协作完成显示页面与逻辑处理的工作了

 

那除了ViewData之外我们还有什么方法由Controller向View文件传值?我们除了能显示aspx文件外还能显示其它的文件么?

 

参考资料:pv版本Asp.net Mvc Framework 三 (Controller与View)

posted @ 2009-03-11 23:52  重典  阅读(15127)  评论(21编辑  收藏  举报