ASP.NET MVC 之Controller & Action (3)

来源:互联网 发布:音频直播软件 编辑:程序博客网 时间:2024/04/28 21:26

DEMO2  传递一个参数到View页面

步骤 1:修改DemoController

添加如下代码到DemoContrller

        publicActionResult ShowText(string id)

        {

            ViewData["txt"] = id;

            returnView();

        }

步骤 2:在Views/Demo文件夹中新建一个ShowText.aspx文件,并修改代码如下:

 

<h2><%= this.ViewData["txt"].ToString()%></h2>

 

步骤 3:在浏览器重查看

1.    在地址栏输入 http://localhost:4313/Demo/ShowText/HelloWorld

我们观察一下这个地址,不难发现,在4313后面依次排列的是{controller}/{action}/{id}

,这正是Global.ascx中的Route定义的一样。

4

最后,我将这个Demo的代码贴出来,其中包括另外两种ActionResult的测试

DemoController.cs代码

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Mvc.Ajax;

 

namespace MvcAppDemo1.Controllers

{

    publicclass DemoController: Controller

{

        publicActionResult Index(){

            returnView();

        }

        publicActionResult ShowText(string id){

            ViewData["txt"] = id;

            returnView();

        }

        publicActionResult ToGoogle(){

            returnRedirect("http://www.google.cn/");

        }

        publicActionResult ToIndex(){

            //returnRedirectToAction("ShowText");

            returnRedirectToAction("ShowText", new {controller="Demo",action="ShowText",id="HelloWorld"});

        }

    }

}

Index.aspx文件

<%@ PageTitle=""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>欢迎您的到来</h2>

    <h3>测试ActionResultRedirect </h3><br />

<asp:HyperLink runat="server"

 NavigateUrl="~/Demo/ToGoogle"Text="Google"></asp:HyperLink>

    <h3>测试ActionResultRedirectToAction</h3>

    <asp:HyperLink runat="server"

 NavigateUrl="~/Demo/ToIndex"Text="ShowText"></asp:HyperLink>

</asp:Content>

 

探讨:我们是否可以如此调用

public ActionResultToIndexTest(){

            returnthis.Index();  //调用同一目录下的Index

        }

    运行出现异常,信息如下

The view 'ToIndexTest' or itsmaster was not found. The following locations were searched:
~/Views/Demo/ToIndexTest.aspx
~/Views/Demo/ToIndexTest.ascx
~/Views/Shared/ToIndexTest.aspx
~/Views/Shared/ToIndexTest.ascx

我们先看看Index方法的代码

public ActionResultIndex(){

            returnView();

        }

可以看到,return View()并没有指定参数,所以,调用它时,它会使用和当前Action 同名的View,所以找不到Index

我们可以修改Index 方法

public ActionResultIndex(){

            returnView(Index);

        }

这样就完成了。

原创粉丝点击