zoukankan      html  css  js  c++  java
  • 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)

  • 相关阅读:
    java.lang.NoSuchMethodError: org.springframework.util.Assert.state(ZLjava/util/function/Supplier;)V
    数据结构中常见的树
    ConcurrentHashMap原理分析
    Synchronized锁升级
    thread.join() 阻塞原理分析
    mysql数据精度丢失问题深入探讨
    ThreadPoolExecutor线程池原理
    JVM的内存区域划分(jdk7和jdk8)
    多线程AQS
    Centos 的防火墙(firewalld,iptables)
  • 原文地址:https://www.cnblogs.com/chsword/p/zd_mvc3.html
Copyright © 2011-2022 走看看