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();
}

 

 

转载于:https://www.cnblogs.com/key1309/p/3480617.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值