MVC学习笔记4 认识View和Controller

首先我们自己新建一个新的Controller

在Controllers上点右键-添加-Controller,选项

mvc

mvc2

VS 自动生成代码:这里我把Controller Name 更改为TestController

        //
        // GET: /Test/

        public ActionResult Index()
        {
            return View();
        }

然后,新建View文件。

当然,除了Controller我们还要建个View,先在Views中建个Test文件夹,然后我们要在其中建个Index.aspx。

不过除此之外ASP.NET MVC还为我们提供了一种新建View的快捷方式。

在对应的Controller的Action中点右键,选择Add View。

mvc

NEXT:

mvc2

接下来是VS的工作了:

<%@ 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">

</asp:Content>

这样好像View和Controller都建好了,可是现在他们还是不能协调工作。

更改Controller

        //
        // GET: /Test/

        public ActionResult Index(string id)
        {
            ViewData["id"] = id;
            return View();
        }

更改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的ID参数的值是:<%=ViewData["id"] %></h2>

</asp:Content>
OK,运行了。
访问 http://localhost:9230/Test/Index/123123 看看效果。
mvc3 

MVC在URL的驱动下,通过Global.asax.cs

   routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );

来获取到id参数的值。

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

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

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

原文地址:https://www.cnblogs.com/dupeng0811/p/1499818.html