标签:各种actionresult actionresult actionresult子类 控制器的各种actionresult
我们所看到的Action都是return View();我们可以看作这个返回值用于解析一个aspx文件。而它的返回类型是ActionResult如
public ActionResult Index() { return View(); }
场景:要返回代码片断,比如Ajax返回一个子页
让我们先建立一个TestController.cs控制器;我们先新建一个Action
public ActionResult Ascx() { return PartialView(); }
@{ 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页面
添加Test控制器下添加一个Action方法
public ActionResult Text() { return Content("这是一段文本"); }这个连视图都不用添加
直接在浏览器中运行 http://localhost:8439/Test/Text 结果是在网页上输出“这是一段文本”这么一行字
有时我们在调用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}
大多时候js文件都是静态的,但有时js文件可能也要动态生成这时我们可以这样输出:
public ActionResult Js() { return JavaScript("var x=0;"); }在浏览器中运行:http://localhost:8439/Test/Js 弹出一个窗体:如下
保存后,用记事本打开Js.js文件 内容是: var x=0;
public ActionResult rdaction() { return RedirectToAction("Text", "Test");//跳转到Test控制下的Text方法 }
public ActionResult rdurl() { return Redirect("http://www.baidu.com"); }在浏览器中运行:http://localhost:8439/Test/rdurl 于是立刻就跳转到百度的首页了。
public ActionResult rdrouting() //跳转到Routing规则 { return RedirectToRoute("Default",//Route名 new { Controller = "Test", Action = "Ascx" }); }
于是就输出 http://localhost:8439/Test/Ascx页面的内容
public ActionResult fn() { return File("d:/123.jpg","jpg/png/JPEG"); }
标签:各种actionresult actionresult actionresult子类 控制器的各种actionresult
原文地址:http://blog.csdn.net/fanbin168/article/details/39505169