很多时候我们会根据UI传入的参数,呈现不同的View。也就是对于同一个Action如何根据请求数据返回不同的View。通常情况下我们会按照如下方法来写,例如:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LoadTreeNodes(TreeViewItem treeViewItem)
{
var nodeText = treeViewItem.Text.ToLower();
if (nodeText == "videos")
{
……
return View("videos");
}
if (nodeText == "news")
{
……
return View("news");
}return View("index");
}

这个时候Action 里面会有很多的if else. 其实,我们忽略了MVC 提供的 ActionNameSelectorAttribute.  我们完全可以自定义ActionNameSelectorAttribute来实现上诉功能。 MVC中的ActionNameAttribute就是继承自ActionNameSelectorAttribute。达到多个Action对应同一个ActionName的目的。

自定义TreeNodeActionSelectorAttribute

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class TreeNodeActionSelectorAttribute : ActionNameSelectorAttribute
{
public string TreeNodeText { get; private set; }
public TreeNodeActionSelectorAttribute(string nodeText)
{
if (String.IsNullOrEmpty(nodeText))
{
throw new ArgumentException("nodeText");
}
this.TreeNodeText = nodeText;
}
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
var text = controllerContext.RequestContext.HttpContext.Request["text"];
return String.Equals(this.TreeNodeText, text, StringComparison.OrdinalIgnoreCase);
}
}

改造Action

[ActionName(“LoadTreeNodes”)]
[TreeNodeActionSelector (“videos”)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LoadVideoNodes(TreeViewItem treeViewItem)
{
……
return View("videos");
}
[ActionName(“LoadTreeNodes”)]
[TreeNodeActionSelector (“news”)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LoadNews(TreeViewItem treeViewItem)
{
……
return View("news");
}
......

有些时候我们可能需要根据用户属于不同的角色,返回不同的View。这种情况也可以通过自定义ActionNameSelectorAttribute来实现。具体如何做请参考:http://www.cnblogs.com/anytao/archive/2009/04/22/1440883.html

最新文章

  1. RSA算法原理
  2. 分享一个UI与业务逻辑分层的框架(三)
  3. Office 365 – SharePoint 2013 Online 之WebPart开发、部署教程
  4. PHP获取用户真实IP
  5. android: 内容提供器简介
  6. HTML5音频,视频播放
  7. JavaScript实现在textbox输入时自动去数据库匹配并找出类似值列出,选择后记得将值填入本textbox及下一个textbox
  8. 铁人系列 (1) uva 10385
  9. JDBC的URL设置allowMultiQueries的原因
  10. hdu 1848 Fibonacci again and again (初写SG函数,详解)
  11. Java程序打包
  12. Android.mk编译.apk .so .jar .a第三方.apk .so .jar .a的方法
  13. iOS_1_加法器
  14. 关于UIView及其子类重绘drawRect
  15. python-django(环境配置)
  16. 谷歌、火狐浏览器 缩放为80% 时,margin值才正确
  17. centos7 centos中apache运行php需要连接mysql一直连不上,telnet访问mysql出错Connection closed by foreign host
  18. 《剑指offer》第四十一题(数据流中的中位数)
  19. (原创)舌尖上的c++--相逢
  20. [django]JsonResponse序列化数据

热门文章

  1. Docker 安装运行MSSQL Server
  2. 阿里云 maven仓库地址配置
  3. 软件素材---linux C语言:linux下获取可执行文件的绝对路径--getcwd函数
  4. java当中请给出一个oracle的helloworld例子
  5. Red Hat操作系统的安装
  6. 字符串char vchar性能对比补充
  7. python正则表达式findall的使用
  8. 手写PE结构解析工具
  9. k8s安装ingress
  10. lock的等效代码