.net 中 ActionResult 返回类型

来源:互联网 发布:北京少儿编程培训班 编辑:程序博客网 时间:2024/05/17 09:12

使用 VS 写后台页面,右击 Controllers 文件夹新建了一个 MVC5 控制器 LicenseController.cs,里面内置了一些代码片段:

public class LicenseController : Controller    {        // GET: Inside/License(此为自动生成的文件夹路径)        public ActionResult Index()        {            return View();        }    }

然后 Views 文件夹下面也生成了相应的 License 文件夹。如果右击 License 文件夹选择添加-视图,会新建一个 .cshtml 文件(所用为 razor 引擎)。return view() 默认返回的是名为 Index 的 .cshtml 文件,与 ActionResult 后面的 Index 是对应的。如果修改视图名称为其他名称,则需要在 View 后括号里添加参数。

于是这就涉及到了 ActionResult 返回类型的问题。

网上有很多关于类名和功能的表格整理,在此只列名字,如果想具体了解可以自己查,个人觉得直接上代码比较靠谱。

ContentResultEmptyResultFileResultHttpStatusCodeResultHttpNotFoundResultHttpUnauthorizedResultJavaScriptResultJsonResultRedirectResultRedirectToRouteResultViewResultBasePartialViewResultViewResult

Push一些相应的代码片段:

        public ContentResult Index()        {            return Content("Hello");       //浏览器显示Hello        }        public EmptyResult Index()        {            return new EmptyResult();     //浏览器空白                    }        public FileResult Index()        {            return File(Server.MapPath("~/demo.jpg"), "application/x-jpg", "demo.jpg");        //浏览器直接下载demo.jpg           }        public HttpNotFoundResult Index()        {            return HttpNotFound();     //报404错误                  }        public HttpUnauthorizedResult Index()        {            return new HttpUnauthorizedResult();     //未授权的页面,跳转到/Account/LogOn                  }        public JavaScriptResult hello()        {            string js = "alert('你还好吗?');";            return JavaScript(js);      //页面显示 alert('你还好吗?');} 并不会执行这个js,要执行这个js可以在任意视图里<script src="@Url.Action("hello")" type="text/javascript"></script>             }        public JsonResult Index()        {            var jsonObj = new            {                Id = 1,                Name = "小铭",                Sex = "男",                Like = "足球"            };            return Json(jsonObj, JsonRequestBehavior.AllowGet);     //返回一个JSON,可以将此代码输出到JS处理展示        }        public RedirectResult Index()        {            return Redirect("~/demo.jpg");      //可以跳转到任意一个路径            return Redirect("http://www.baidu.com");            return Redirect("/list");        }        public RedirectToRouteResult Index()        {            return RedirectToRoute(     //跳转到指定Action            new            {                controller = "Home",                action = "GetName"            });        }        public ViewResult Index()        {            return View();          //这个是最常用的,返回指定视图            //return View("List");            //return View("/User/List");        }        public PartialViewResult Index()        {            return PartialView();          //部分视图,可以作为一个部分引入另外一个视图中,跟View大致相同        }

最后的代码片段来自所有的Controller都继承自System.Web.Mvc.Controller