zoukankan      html  css  js  c++  java
  • [MVC] 自定义ActionSelector,根据参数选择Action

    很多时候我们会根据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

  • 相关阅读:
    [转]ios 判断左右摆动方法与 摇一摇
    UIButton 使用大全
    疑问:xcode中为什么按钮被图片覆盖了,还能响应事件?
    iOS base64 加密解密 通用类
    new BMKMapPoint[index] 和 delete []points 报错
    Xcode 中 如果不自动设置字体大小,则系统默认为17号
    UILabel 详解
    BMKMapView 和 BMKSearch 初始化先后顺序问题
    使用ASIFormDataRequset类 获取webservice 接口数据
    实现 scrollview 默认显示指定的页码
  • 原文地址:https://www.cnblogs.com/sjqq/p/9553846.html
Copyright © 2011-2022 走看看