首页 > 代码库 > 控制器-各种ActionResult【2】
控制器-各种ActionResult【2】
控制器-各种ActionResult
我们所看到的Action都是return View();我们可以看作这个返回值用于解析一个aspx文件。而它的返回类型是ActionResult如
public ActionResult Index() { return View(); }
除了View()之外那我们这里还能用于返回什么值呢?
<1>ascx页面
场景:要返回代码片断,比如Ajax返回一个子页
让我们先建立一个TestController.cs控制器;我们先新建一个Action
public ActionResult Ascx() { return PartialView(); }
然后给这个Action添加一个视图Ascx.cshtml
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Ascx</title> </head> <body> <div> <table border="1"> <tr><th>中国</th><th>美国</th><th>英国</th></tr> <tr><th>湖南</th><th>纽约</th><th>巴黎</th></tr> </table> </div> </body> </html>在浏览器中运行 http://localhost:8439/Test/Ascx 得到的结果是一个ascx页面
<2>返回文本
添加Test控制器下添加一个Action方法
public ActionResult Text() { return Content("这是一段文本"); }这个连视图都不用添加
直接在浏览器中运行 http://localhost:8439/Test/Text 结果是在网页上输出“这是一段文本”这么一行字
<3>返回Json
有时我们在调用Ajax时还会要求返回对象为Json序列化的结果,如:
public ActionResult ShowJson() { var userinfo = new { Name = "奥巴马", Age = 56 }; return Json(userinfo, JsonRequestBehavior.AllowGet); //var tempObj = new { Controller = "DemoController", Action = "JsonResultDemo" }; //return Json(tempObj,JsonRequestBehavior.AllowGet); //JsonRequestBehavior.AllowGet表示:允许来自客户端的 HTTP GET 请求 //return Json(User, JsonRequestBehavior.AllowGet); }在浏览器中运行 http://localhost:8439/Test/ShowJson 然后就弹出一个窗体让你保存ShowJson.json文件。
保存图片后,用记事本打开文件,文件的内容是 :{"Name":"奥巴马","Age":56}
<4>输出JS文件
大多时候js文件都是静态的,但有时js文件可能也要动态生成这时我们可以这样输出:
public ActionResult Js() { return JavaScript("var x=0;"); }在浏览器中运行:http://localhost:8439/Test/Js 弹出一个窗体:如下
保存后,用记事本打开Js.js文件 内容是: var x=0;
<5>页面跳转
1.跳转到Action
public ActionResult rdaction() { return RedirectToAction("Text", "Test");//跳转到Test控制下的Text方法 }
在浏览器中运行:http://localhost:8439/Test/rdaction 于是立刻就跳转到 http://localhost:8439/Test/Text页面了,于是输出
2.跳转到Url
public ActionResult rdurl() { return Redirect("http://www.baidu.com"); }在浏览器中运行:http://localhost:8439/Test/rdurl 于是立刻就跳转到百度的首页了。
3.跳转到Routing规则
public ActionResult rdrouting() //跳转到Routing规则 { return RedirectToRoute("Default",//Route名 new { Controller = "Test", Action = "Ascx" }); }
在浏览器中运行:http://localhost:8439/Test/rdrouting 于是立刻就跳转到 Test控制器下的Ascx方法了,即跳转到http://localhost:8439/Test/Ascx 页面了
于是就输出 http://localhost:8439/Test/Ascx页面的内容
<6>显示文件
public ActionResult fn() { return File("d:/123.jpg","jpg/png/JPEG"); }
在浏览器中运行:http://localhost:8439/Test/fn 弹出一个对话框:如下
点击保存后,选择用图片查看器打开。显示出了 D盘下的123.jpg图片
控制器-各种ActionResult【2】
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。