Action的返回值类型总结

Action的返回值

 

MVC 中的 ActionResult是其他所有Action返回类型的基类,下面是我总结的返回类型,以相应的帮助方法:          

 

下面是这些方法使用的更详细的例子

一、返回View     View()方法的几种重载:

public ViewResult Index() {
    return View();
}
 
public ViewResult Index() {
    return View("Index""_AlternateLayoutPage");
}
 
public ViewResult Index() {
    return View("~/Views/Other/Index.cshtml");
}

 

 

二、返回partialView

       public ActionResult PartialViewResult()
        {
            return PartialView();
        }
 
        //禁止直接访问的ChildAction
        [ChildActionOnly]
        public ActionResult ChildAction()
        {
            return PartialView();
        }

 们直接右键当前的Action名称就可以创建与Action同名的View,无参数的情况下,PartialView返回的就是与Action同名的View

 

 

三、跳转的几种实现方 

1、通过静态URL进行跳转:
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字符串

public ActionResult Json() 
{
        Dictionary<string,object> dic = new Dictionary<stringobject>(); 
        dic.Add("id",100); 
        dic.Add("name","hello"); 
        return Json(dic, JsonRequestBehavior.AllowGet); 

主要用于返回json格式对象,可以用ajax操作;
注意:需要设置参数,JsonRequestBehavior.AllowGet,否则会提示错误:此请求已被阻止,因为当用在GET 请求中时,会将敏感信息透漏给第三方网站

若要允 GET 请求,请将JsonRequestBehavior设置为AllowGet

 

 

 

 五、返回ContentResult

public ActionResult Content() 

       return  Content("Test Content""text/html"); // 可以指定文本类型 

页面输出Test Content;此类型多用于在ajax操作中需要返回的文本内容

 

 

 六、返回JavaScriptResult

public ActionResult JavaScript() 

       string str =string.Format("alter('{0}');""弹出窗口"); 
       return JavaScript(str); 

这里并不会直接响应弹出窗口,需要用页面进行再一次调用这个可以方便根据不同逻辑执行不同的js操作



 

七、返回FileResult

public ActionResult File() 

       string fileName ="~/Content/test.zip"// 文件名 
        string downFileName ="文件显示名称.zip"// 要在下载框显示的文件名 
         return File(fileName,"application/octet-stream", downFileName); 

直接下test.zip后保存到本地则为"文件显示名称.zip"



 八、返回404、401

 

返回404
public HttpStatusCodeResult StatusCode() {
     return HttpNotFound();
}


返回401
public HttpStatusCodeResult StatusCode() {
    return new HttpUnauthorizedResult();
}

 

 

posted on 2013-12-18 16:34  Creater  阅读(4110)  评论(0编辑  收藏  举报

导航