首页 > 代码库 > ASP.NET MVC Controllers and Actions

ASP.NET MVC Controllers and Actions

MVC应用程序里的URL请求是通过控制器Controller处理的,不管是请求视图页面的GET请求,还是传递数据到服务端处理的Post请求都是通过Controller来处理的,先看一个简单的Controlller:

public class DerivedController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Message = "Hello from the DerivedController Index method";   //动态数据
        return View("MyView");   //指定返回的View
    }
}

是个DerivedController,那么对应处理的URL就是这样的:localhost:1042/Derived/Index,并且Index这个Action指定了返回的视图是MyView,而不是同名的Index视图,那么就需要新建一个视图MyView。在Index这个Action方法内右键 - 添加视图 - MyView,或者在解决方案的Views目录下新建一个Derived目录,再右键 - 新建视图 - MyView:

@{
    ViewBag.Title = "MyView";
}
<h2>
    MyView</h2>
Message: @ViewBag.Message

直接Ctrl+F5运行程序浏览器定位到的url是:localhost:1042,看看路由的定义:

routes.MapRoute(
    "Default", // 路由名称
    "{controller}/{action}/{id}", // 带有参数的 URL
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值
);

注意路由的最后一行:new { controller = "Home", action = "Index", id = UrlParameter.Optional }
都给默认值了,那么URL:localhost:1042 其实就是:localhost:1042/Home/Index id是可选参数。
localhost:1042/Home/Index这个Url找的Controller自然是HomeController,Index对应的是HomeController下的Index这个Action,显然没有HoomeController,自然会报404错。
解决方法:
1.把路由的默认值修改成:

new { controller = "Derived", action = "Index", id = UrlParameter.Optional }

2.在浏览器的url栏里手动输入:localhost:1042/Derived/index

可以通过上下文对象Context取一些参数:

string userName = User.Identity.Name;
string serverName = Server.MachineName;
string clientIP = Request.UserHostAddress;
DateTime dateStamp = HttpContext.Timestamp;

跟普通的WebForm里一样,可以通过Request.Form接收传递过来的参数:

string oldProductName = Request.Form["OldName"];
string newProductName = Request.Form["NewName"];

取URL里/路由的参数:

string city = RouteData.Values["city"].ToString();

给Controller传参:

public ActionResult ShowWeatherForecast(string city, DateTime forDate)
{
    ViewBag.City = city;
    ViewBag.ForDate = forDate;
    return View();
}

对应的a标签是这样的:
@Html.ActionLink("查看天气(传参)", "ShowWeatherForecast", new { city = "北京", forDate = @DateTime.Now })
再添加对应的视图:

@{
    Layout = null;
}
要查询的是:@ViewBag.City 的天气,查询的时间是:@ViewBag.ForDate

运行下程序ShowWeatherForecast视图就显示了:
要查询的是:北京 的天气,查询的时间是:2013/11/25 21:08:04

当然也可以不传参但是提供默认值:

@Html.ActionLink("查看天气(默认值) ", "ShowWeatherForecast", new { forDate = @DateTime.Now })

没有传city,看Controller:

public ActionResult ShowWeatherForecast(DateTime forDate, string city = "合肥")
{
    ViewBag.City = city;
    ViewBag.ForDate = forDate;
    return View();
}

视图显示:
要查询的是:合肥 的天气,查询的时间是:2013/11/25 21:16:35
默认值已经起作用了。

控制器里获取路由数据:

public string Index()
{
    string controller = (string)RouteData.Values["controller"];
    string action = (string)RouteData.Values["action"];

    return string.Format("Controller: {0}, Action: {1}", controller, action);
}

自然浏览器就会显示:Controller: Derived, Action: index
Action里实现跳转:

public void Index()
{
    Response.Redirect("/Derived/ShowWeatherForecast");
}

使用Response.Redirect实现跳转还比较偏WebForm化,MVC里更应该这么跳转:

public ActionResult Index()
{
    return new RedirectResult("/Derived/ShowWeatherForecast");
}

之前都是类似的Action都是Return的View这里却Return的却是RedirectResult,这就得看方法的返回值了,方法的返回值是ActionResult,并不仅仅是ViewResult,可以理解为ActionResult是ViewResult和RedirectResult等等的基类。
这里甚至可以直接返回视图文件的物理路径:

return View("~/Views/Derived/ShowWeatherForecast.cshtml");

常用的Action返回值类型有:

技术分享

技术分享

跳转到别的Action:

public RedirectToRouteResult Redirect() { 
    return RedirectToAction("Index"); 
} 

上面的方法是跳转到当前Controller下的另外一个Action,如果要跳转到别的Controller里的Action:

return RedirectToAction("Index", "MyController"); 

返回普通的Text数据:

public ContentResult Index() { 
    string message = "This is plain text"; 
    return Content(message, "text/plain", Encoding.Default); 
} 

返回XML格式的数据:

public ContentResult XMLData() { 
 
    StoryLink[] stories = GetAllStories(); 
 
    XElement data = http://www.mamicode.com/new XElement("StoryList", stories.Select(e => { 
        return new XElement("Story", 
            new XAttribute("title", e.Title), 
            new XAttribute("description", e.Description), 
            new XAttribute("link", e.Url)); 
    })); 
 
    return Content(data.ToString(), "text/xml"); 
} 

返回JSON格式的数据(常用):

[HttpPost] 
public JsonResult JsonData() { 
 
    StoryLink[] stories = GetAllStories(); 
    return Json(stories); 
} 

文件下载:

public FileResult AnnualReport() { 
    string filename = @"c:\AnnualReport.pdf"; 
    string contentType = "application/pdf"; 
    string downloadName = "AnnualReport2011.pdf"; 
 
    return File(filename, contentType, downloadName); 
} 

触发这个Action就会返回一个文件下载提示:

技术分享

返回HTTP状态码:

//404找不到文件
public HttpStatusCodeResult StatusCode() { 
    return new HttpStatusCodeResult(404, "URL cannot be serviced"); 
}

//404找不到文件
public HttpStatusCodeResult StatusCode() { 
    return HttpNotFound(); 
}

//401未授权
public HttpStatusCodeResult StatusCode() { 
    return new HttpUnauthorizedResult(); 
}

返回RSS订阅内容:

public RssActionResult RSS() { 
    StoryLink[] stories = GetAllStories(); 
    return new RssActionResult<StoryLink>("My Stories", stories, e => { 
        return new XElement("item", 
            new XAttribute("title", e.Title), 
            new XAttribute("description", e.Description), 
            new XAttribute("link", e.Url)); 
    }); 
} 

触发这个Action就会浏览器机会显示:

技术分享

ASP.NET MVC Controllers and Actions