MVC中常用的返回值方法

我们上边所看到的Action都是return View();我们可以看作这个返回值用于解析一个aspx文件。而它的返回类型是ActionResult如

 
  1. public ActionResult Index()
  2. {
  3. return View();
  4. }

除了View()之外那我们这里还能用于返回什么值呢?

一、ascx页面

场景:要返回代码片断,比如Ajax返回一个子页

我们先新建一个Action

 
  1. public ActionResult Ascx()
  2. {
  3. return PartialView();
  4. }

我们下面再建一个View,仍然是在Action中点右键,AddView。

 注意图中勾选。

于是新建了一个ascx页,我们将之少做改写一下

 
  1. <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
  2. <div>
  3. 得到一个DIV
  4. </div>

运行,得到页面

二、返回文本

除了上述情况,有时我们还会仅返回一段文本。

此时我们可以使用以下Action形式:

 
  1. public ActionResult Text(){
  2. return Content("这是一段文本");
  3. }

三、返回Json

有时我们在调用Ajax时还会要求返回对象为Json序列化的结果,如:

 
  1. public ActionResult ShowJson()
  2. {
  3. var m = new EiceIndexModel
  4. {
  5. Name = "邹健",
  6. Sex = true
  7. };
  8. return Json(m);
  9. }

返回文本:

 
  1. {"Name":"邹健","Sex":true}

四、输出JS文件

大多时候js文件都是静态的,但有时js文件可能也要动态生成这时我们可以这样输出

 
  1. public ActionResult Js()
  2. {
  3. return JavaScript("var x=0;");
  4. }

我们访问之,得到一个正常页面但其Content-Type:application/x-javascript; charset=utf-8

五、页面跳转

1.跳转到Url

 
  1. public ActionResult rdurl()
  2. {
  3. return Redirect("http://www.baidu.com");
  4. }

2.跳转到Action

 
  1. public ActionResult rdaction()
  2. {
  3. return RedirectToAction("Index","Eice");
  4. }

3.跳转到Routing规则

 
  1. public ActionResult rdrouting()
  2. {
  3. return RedirectToRoute("Default",//Route名
  4. new{
  5. Controller = "Eice",
  6. Action = "Index"
  7. });
  8. }

六、显示文件

 
  1. public ActionResult fn()
  2. {
  3. return File(
  4. "/Content/site.css"//文件路径
  5. , "text/css"//文件类型
  6. );
  7. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值