您的位置:首页 > 编程语言 > ASP

让ASP.NET MVC的Controller输出不同类型数据

2010-05-30 13:58 288 查看
ASP.NET MVC中,可以通过返回不同类型的ActionResult来输出不同内容,比如ViewResult会输出视图页,JsonResult会输出Json数据等等。

而有时会遇到同一个Controller需要支持输出不同类型的情况,比如正常查看一个用户的资料页时, 用/User/{id}就可以访问到;而在JavaScript或其它系统中需要查看用户资料,又希望/User/{id}能返回Json数据。 这种情况可以通过构建一个自定义ActionResult来实现,根据参数返回默认的ViewResult,或者将Model序列化为指定的类型输出,其实就是控制Model的输出行为。输出类型的参数,可以通过两种方式来传递,一个种传统的Get或Post传参:/User/{id}?rtype=json;另一种可以通过Http请求的ContentType参数来指定类型:request.ContentType = “json”.

附参考代码:

public class AutoResult : ActionResult
{
public string ViewName { get; set; }
public object Model { get; set; }

public override void ExecuteResult(ControllerContext context)
{
string type = context.HttpContext.Request["rtype"];
if (string.IsNullOrEmpty(type))
{
type = context.HttpContext.Request.ContentType;
}

if (!string.IsNullOrEmpty(type))
{
switch (type.ToLower())
{
case "json":
new NJsonResult(Model).ExecuteResult(context);
break;
case "binary":
new BinaryResult(Model).ExecuteResult(context);
break;
case "xml":
new XmlResult(Model).ExecuteResult(context);
break;
default:
context.HttpContext.Response.Output.Write("无法识别的类型");
break;
}
}
else
{
context.Controller.ViewData.Model = Model;
ViewResult viewResult = new ViewResult() { ViewName = ViewName, ViewData = context.Controller.ViewData };
viewResult.ExecuteResult(context);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: