当前位置:  开发笔记 > 编程语言 > 正文

强类型的url动作

如何解决《强类型的url动作》经验,为你挑选了0个好方法。

我读了很多类似的帖子和博客

ASP.NET MVC中基于代理的强类型URL生成

但他们中没有一个人真的做我想做的事.目前我有一个混合方法,如:

// shortened for Brevity
public static Exts
{  
  public string Action(this UrlHelper url, 
    Expression> expression)
    where T : ControllerBase
  {
    return Exts.Action(url, expression, null);
  }

  public string Action(this UrlHelper url, 
    Expression> expression,
    object routeValues)
    where T : ControllerBase
  {
    string controller;
    string action;

    // extension method 
    expression.GetControllerAndAction(out controller, out action);

    var result = url.Action(action, controller, routeValues);

    return result;
  }
}

如果你的控制器方法没有任何参数,那么效果很好:

public class MyController : Controller 
{
  public ActionResult MyMethod()
  {
    return null;
  }
  public ActionResult MyMethod2(int id)
  {
    return null;
  }
}

然后我可以:

Url.Action(c => c.MyMethod())

但是如果我的方法接受一个参数,那么我必须传递一个值(我永远不会使用):

Url.Action(c => c.MyMethod2(-1), new { id = 99 })

所以问题是有一种方法可以改变扩展方法,仍然要求第一个参数是一个在类型T上定义的方法,确保返回参数是一个ActionResult没有实际指定参数的类型,如:

Url.Action(c => c.MyMethod2, new { id = 99 })

所以这会传递一个指向方法的指针(比如反射MethodInfo)而不是Func<>它,所以它不会关心参数.如果有可能,那签名会是什么样子?

推荐阅读
mobiledu2402852357
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有