DEMO2 传递一个参数到 View 页面
步骤 1 :修改 DemoController
添加如下代码到 DemoContrller 中
public ActionResult ShowText(string id)
{
ViewData["txt" ] = id;
return View();
}
步骤 2 :在Views/Demo 文件夹中新建一个ShowText.aspx 文件,并修改代码如下:
< h2 > <% = this .ViewData["txt" ].ToString()%> </ h2 >
步骤 3 :在浏览器重查看
1. 在地址栏输入 http://localhost:4313/Demo/ShowText/Hello World
我们观察一下这个地址,不难发现,在4313 后面依次排列的是{controller}/{action}/{id}
, 这正是Global.ascx 中的Route 定义的一样。
最后,我将这个 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
{
public class DemoController : Controller
{
public ActionResult Index(){
return View();
}
public ActionResult ShowText(string id){
ViewData["txt" ] = id;
return View();
}
public ActionResult ToGoogle(){
return Redirect("http://www.google.cn/" );
}
public ActionResult ToIndex(){
//return RedirectToAction("ShowText");
return RedirectToAction("ShowText" , new {controller="Demo" ,action="ShowText" ,id="Hello World" });
}
}
}
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">
< h2 > 欢迎您的到来</ h2 >
< h3 > 测试ActionResult 的Redirect </ h3 >< br />
< asp : HyperLink runat ="server"
NavigateUrl ="~/Demo/ToGoogle" Text ="Google"></ asp : HyperLink >
< h3 > 测试ActionResult 的RedirectToAction</ h3 >
< asp : HyperLink runat ="server"
NavigateUrl ="~/Demo/ToIndex" Text ="ShowText"></ asp : HyperLink >
</ asp : Content >
探讨:我们是否可以如此调用
public ActionResult ToIndexTest(){
return this .Index(); // 调用同一目录下的Index
}
运行出现异常,信息如下
The view 'ToIndexTest' or its
master 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 ActionResult Index(){
return View();
}
可以看到, return View() 并没有指定参数,所以,调用它时,它会使用和当前 Action 同名的 View, 所以找不到 Index 。
我们可以修改 Index 方法
public ActionResult Index(){
return View( “ Index ” );
}
这样就完成了。