MVC4.0 利用IActionFilter实现单一Action返回多种结果

延续MVC4.0 实现单一Action返回多种结果,我们实现了在一个Action中根据前台请求方式的不同和请求内容的不同返回了多个结果,但是这种返回多个结果的业务逻辑并不通用。如果现在年纪Action也要实现这样的业务逻辑,怎么办?除了复制代码,索性MVC为我们提供了完美的机制,在多个控制器上重用统一的业务逻辑规则:IActionFilter拦截器。

1.定义一个多响应Result拦截器MultipleResponseResultFilter

    /// <summary>
/// 多响应Result拦截器
/// </summary>
public class MultipleResponseResultFilter : FilterAttribute, IActionFilter
{
public string PartialViewName { get; set; } /// <summary>
/// Action执行后
/// </summary>
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
var request = filterContext.HttpContext.Request;
var viewResult = filterContext.Result as ViewResult; if (viewResult == null)
return; if (request.IsPartialRequest())
{
filterContext.Result = new PartialViewResult
{
TempData = viewResult.TempData,
ViewData = viewResult.ViewData,
ViewName = PartialViewName,
};
} if (request.IsJsonRequest())
{
filterContext.Result = new JsonResult
{
Data = viewResult.Model,
};
}
} /// <summary>
/// Action执行前
/// </summary>
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{ }
}

2.Action调用实现(局部视图PartialViewName为必须值)

        [MultipleResponseResultFilter(PartialViewName="PartialStudent")]
public ActionResult Student()
{
return View(new { Name = "小明", Sex = "女" });
}

3.Html调用代码如下:

<body>
<h3>view视图</h3>
<div>我是小明</div> <h3>PartialView视图:</h3>
<div id="partial"></div> <h3>Json数据:</h3>
<div id="json"></div> <script src="~/Content/js/jquery-1.10.2.min.js"></script> <script type="text/javascript">
$(function () {
$('#partial').load('@Url.Action("Student", "Home", new { area=string.Empty, format="partial" })'); $.post('@Url.Action("Student", "Home")', { format: 'json' }, function (res) {
if (res) {
$('#json').html(res.Name);
}
}, 'json')
})
</script>
</body>
上一篇:jquery.autocomplete自动补全功能


下一篇:OpenLayer 3 鼠标位置坐标显示控件