2.操作方法的返回值类型的种类
目前ASP.NET MVC3默认提供了11种ActionResult的实现
在System.Web.Mvc命名空间
ActionResult
ContentResult
EmptyResult
FileResult
HttpStatusCodeResult
HttpNotFoundResult
HttpUnauthorizedResult
JavaScriptResult
JsonResult
RedirectResult
RedirectToRouteResult
ViewResultBase
PartialViewResult
ViewResult
代码示例:
- usingSystem.Web.Mvc;
- namespaceMvcApplication1.Controllers
- {
- publicclassActionResultController: Controller
- {
- publicActionResultIndex()
- {
- returnView();
- }
- publicActionResultContentResult()
- {
- returnContent("Hi, 我是ContentResult结果");
- }
- publicActionResultEmptyResult()
- {
- //空结果当然是空白了!
- //至于你信不信, 我反正信了
- returnnewEmptyResult();
- }
- publicActionResultFileResult()
- {
- varimgPath = Server.MapPath("~/demo.jpg");
- returnFile(imgPath, "application/x-jpg", "demo.jpg");
- }
- publicActionResultHttpNotFoundResult()
- {
- returnHttpNotFound("Page Not Found");
- }
- publicActionResultHttpUnauthorizedResult()
- {
- //未验证时,跳转到Logon
- returnnewHttpUnauthorizedResult();
- }
- publicActionResultJavaScriptResult()
- {
- stringjs = "alert(\"Hi, I''m JavaScript.\");";
- returnJavaScript(js);
- }
- publicActionResultJsonResult()
- {
- varjsonObj = new
- {
- Id = 1,
- Name = "小铭",
- Sex = "男",
- Like = "足球"
- };
- returnJson(jsonObj, JsonRequestBehavior.AllowGet);
- }
- publicActionResultRedirectResult()
- {
- returnRedirect("~/demo.jpg");
- }
- publicActionResultRedirectToRouteResult()
- {
- returnRedirectToRoute(new{
- controller = "Hello", action = ""
- });
- }
- publicActionResultViewResult()
- {
- returnView();
- }
- publicActionResultPartialViewResult()
- {
- returnPartialView();
- }
- //禁止直接访问的ChildAction
- [ChildActionOnly]
- publicActionResultChildAction()
- {
- returnPartialView();
- }
- //正确使用ChildAction
- publicActionResultUsingChildAction()
- {
- returnView();
- }
- }
- }
请注意,个别的操作方法结果在执行时,他们返回的HTTP状态码及ContentType有差别的.~另外如果要知道ContentType到底有多少种设置可参考
3.操作方法的参数
在本小节,我仅仅演示如何使URL参数映射到操作方法的参数,对于更复杂的用法,我将会留到 模型 的章节去讲解.
首先我们需要先添加一个新的路由映射,然后在设置3个占位符参数,它们分别是p1, p2, p3.然后将p1约束为仅字母与数字的组合,p2约束为仅数字,p3没有添加约束.
- routes.MapRoute(
- "UsingParams",
- "p/{p1}/{p2}/{p3}",
- new{
- controller = "Home",
- action = "UsingParams"
- },
- new{ p1 = "[a-z0-9]+", p2 = @"d+"}
- );
在