zoukankan      html  css  js  c++  java
  • MVC学习第三节:Controller与View

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

    一、新建Controller

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

    image  
    之后出现一个对话框:

    image  
    这里我们将之起名为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。

    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文件外还能显示其它的文件么?

  • 相关阅读:
    Spring Cloud 入门教程6、Hystrix Dashboard监控数据聚合(Turbine)
    Spring Cloud 入门教程5、服务容错监控:Hystrix Dashboard
    Spring Cloud 入门教程4、服务容错保护:断路器(Hystrix)
    Spring Cloud 入门教程3、服务消费者(Feign)
    JS==和===总结
    怀疑与批判
    Java多线程速记手册
    编译原理
    C系、Java、JavaScript、C#、PHP、Swift基本语法对比
    单例模式番外篇
  • 原文地址:https://www.cnblogs.com/ayzhanglei/p/2426526.html
Copyright © 2011-2022 走看看