Action的返回值
MVC 中的 ActionResult是其他所有Action返回类型的基类,下面是我总结的返回类型,以相应的帮助方法:
下面是这些方法使用的更详细的例子
一、返回View View()方法的几种重载:
return View();
}
public ViewResult Index() {
return View( " Index ", " _AlternateLayoutPage ");
}
public ViewResult Index() {
return View( " ~/Views/Other/Index.cshtml ");
}
二、返回partialView
{
return PartialView();
}
// 禁止直接访问的ChildAction
[ChildActionOnly]
public ActionResult ChildAction()
{
return PartialView();
}
我们直接右键当前的Action名称就可以创建与Action同名的View,无参数的情况下,PartialView返回的就是与Action同名的View。
三、跳转的几种实现方式
public RedirectResult Redirect() {
return Redirect( " /Example/Index ");
}
2、通过RedirectToRoute方法跳转:
public RedirectToRouteResult Redirect() {
return RedirectToRoute( new {
controller = " Example ",
action = " Index ",
ID = " MyID "
});
}
3、通过RedirectToAction方法跳转:
public RedirectToRouteResult Redirect() {
return RedirectToAction( " Index ", " Basic "); // 如果只有action名称的话,Controller默认为当前Controller
}
四、返回json字符串
{
Dictionary< string, object> dic = new Dictionary< string, object>();
dic.Add( " id ", 100);
dic.Add( " name ", " hello ");
return Json(dic, JsonRequestBehavior.AllowGet);
}
主要用于返回json格式对象,可以用ajax操作;
注意:需要设置参数,JsonRequestBehavior.AllowGet,否则会提示错误:此请求已被阻止,因为当用在GET 请求中时,会将敏感信息透漏给第三方网站。
若要允许 GET 请求,请将JsonRequestBehavior设置为AllowGet。
五、返回ContentResult
{
return Content( " Test Content ", " text/html "); // 可以指定文本类型
}
页面输出“Test Content”;此类型多用于在ajax操作中需要返回的文本内容
六、返回JavaScriptResult
{
string str = string.Format( " alter('{0}'); ", " 弹出窗口 ");
return JavaScript(str);
}
七、返回FileResult
{
string fileName = " ~/Content/test.zip "; // 文件名
string downFileName = " 文件显示名称.zip "; // 要在下载框显示的文件名
return File(fileName, " application/octet-stream ", downFileName);
}
直接下载test.zip后保存到本地则为"文件显示名称.zip"
八、返回404、401
return HttpNotFound();
}
返回401
public HttpStatusCodeResult StatusCode() {
return new HttpUnauthorizedResult();
}