ASP.NET MVC中Controller返回值类型ActionResult
2016-04-28 01:49
731 查看
1、返回ViewResult视图结果,将视图呈现给网页
public class TestController : Controller { //必须存在Controller\Test\Index.cshtml文件 public ActionResult Index() { return View(); } }
2、 返回PartialViewResult部分视图结果,主要用于返回部分视图内容
//在View/Shared目录下创建ViewUserControl.cshtml部分视图 public ActionResult UserControl() { return PartialView("ViewUserControl"); }
3、 返回ContentResult用户定义的内容类型
public ActionResult Content() { return Content("Test Content", "text/html"); // 可以指定文本类型 }
4、 返回JsonResult序列化的Json对象
public ActionResult Index() { //主要用于返回json格式对象,可以用ajax操作; //注意:需要设置参数,JsonRequestBehavior.AllowGet, //否则会提示错误:此请求已被阻止,因为当用在 GET 请求中时,会将敏感信息透漏给第三方网站。 //若要允许 GET 请求,请将 JsonRequestBehavior 设置为 AllowGet。 Dictionary<string, object> dic = new Dictionary<string, object>(); dic.Add("id", 100); dic.Add("name", "hello"); return Json(dic, JsonRequestBehavior.AllowGet); }
5、返回JavaScriptResult可在客户端执行的脚本
public ActionResult Index() { //但这里并不会直接响应弹出窗口,需要用页面进行再一次调用。 //这个可以方便根据不同逻辑执行不同的js操作 string str = string.Format("alter('{0}');", "弹出窗口"); return JavaScript(str); }
6、返回FileResult要写入响应中的二进制输出,一般可以用作要简单下载的功能
public ActionResult Index() { //直接下载test.zip后保存到本地则为"文件显示名称.zip string fileName = "~/Content/test.zip"; // 文件名 string downFileName = "文件显示名称.zip"; // 要在下载框显示的文件名 return File(fileName, "application/octet-stream", downFileName); }
7.返回Null或者Void数据类型的EmptyResult
public ActionResult Index() { return null; }
8、重定向方法:Redirect / RedirectToAction / RedirectToRoute
public class TestController : Controller { public ActionResult Index(int id = 0, string name = "") { return View(); } //Redirect:直接转到指定的url地址 public ActionResult Redirect() { return Redirect("http://www.baidu.com"); } //RedirectToAction:直接使用 Action Name 进行跳转,也可以加上ControllerName public ActionResult RedirectResult() { return RedirectToAction("Index", "Test", new { id = 100, name = "liu" }); } //RedirectToRoute:指定路由(RouteConfig注册的路由规则)进行跳转 public ActionResult RedirectRouteResult() { return RedirectToRoute("Default", new { controller = "Test", action = "Index" }); } }
相关文章推荐
- Aspnetpager对GridView分页并顺利导出Excel
- ASP.NET项目开发中日期控件DatePicker如何使用
- ASP.NET使用My97DatePicker日期控件实例
- ASP.NET My97DatePicker日期控件实现OA日期记事功能
- 在ASP.NET 2.0中操作数据:创建一个业务逻辑层
- ASP.NET Core的配置(4):多样性的配置来源[下篇]
- Asp.net 面向接口可扩展框架之类型转化基础服务
- casperjs的高级应用
- asp.net 数据验证控件的使用实例
- ASP.NET MVC数组模型绑定详解
- ASP.NET C#生成下拉列表树实现代码
- ASP.NET 上传图片添加文字、Logo水印
- 【中国互联网不眠夜】Struts2漏洞百出,OneRASP鼎力相助
- 【中国互联网不眠夜】Struts2漏洞百出,OneRASP鼎力相助
- 【中国互联网不眠夜】Struts2漏洞百出,OneRASP鼎力相助
- 构建高性能ASP.NET应用的几点建议
- 使用veil-evasion+metasploit生成基于python的后门软件
- 【ASP.NET MVC 回顾】HtmlHepler应用-分页组件
- 什么是ASP?如何打开ASP文件
- ASP.NET: Bind Dropdownlist With Images