我正在尝试创建一个根据控制器名称和操作名称创建 url 的方法。我不想使用魔术字符串,所以我正在考虑一种采用 lambda 表达式作为参数的方法。
棘手的部分是,我不想在操作方法上指定任何参数。因此,例如,如果我有这个控制器:
public class HomeController : IController
{
public Index(int Id)
{
..
}
}
我想这样调用该方法:
CreateUrl<HomeController>(x=>x.Index);
我想出的方法的签名是:
public string CreateUrl<TController>(Expression<Action<TController>> action) where TController : IController
但这并不能解决跳过参数的问题。我的方法只能使用指定的参数进行调用,如下所示:
CreateUrl<HomeController>(x=>x.Index(1));
Is it possible tospecify an action or method on a controller without to set the parameters?
I'm trying to create a method which creates a url based on the controllername and the actionname. I don't want to use magic strings, so I was thinking about a method taking a lambda expression as a parameter.
The tricky part is, I don't want to specify any parameters on the action method. So for instance if I have this controller:
public class HomeController : IController
{
public Index(int Id)
{
..
}
}
I would like to call the method like this:
CreateUrl<HomeController>(x=>x.Index);
The signature of the method I've come up with is:
public string CreateUrl<TController>(Expression<Action<TController>> action) where TController : IController
But this does not solve the problem of skipping the parameters. My method can only be called with the parameter specfied like this:
CreateUrl<HomeController>(x=>x.Index(1));
Is it possible to specify an action or method on a controller without having to set the parameters?
发布评论
评论(3)
除非您的操作方法中有可选或默认参数,否则不可能省略表达式树中的参数。由于表达式树可以编译为可运行的代码,因此表达式仍由编译器验证,因此它需要是有效的代码 - 方法参数等。
正如下面 Dan 的示例所示,提供默认参数非常简单:
public ActionResult Index(int Id = 0)
此外,由于操作方法必须返回某种结果,因此您的 Expression 类型应该是
表达式>
,这将允许从表达式中定义的方法返回任何类型的对象。一定要看看 MVCContrib。
It is not possible to omit the parameters with an expression tree unless you have optional or default parameters within your action methods. Because expression trees can be compiled into runnable code, the expression is still validated by the compiler so it needs to be valid code - method parameters and all.
As in Dan's example below, supplying a default parameter is as simple as:
public ActionResult Index(int Id = 0)
Additionally, since action methods have to return some sort of result, your Expression should be of type
Expression<Func<TController, object>>
, which will allow for any type of object to be returned from the method defined in the expression.Definitely check out MVCContrib.
使用T4MVC。这是删除所有魔法字符串并执行更多操作的最佳选择
Use T4MVC. This is best option to remove all magic strings and do much more
正如 bdowden 所说,您必须提供参数或参数的默认值,如下所示:
此外,如果您使用 MVCContrib 这些扩展方法已经存在。 (查看 URLHelperExtentions)。
As bdowden said, you must provide parameters or defaults for the parameters as such:
In addition, if you use MVCContrib these extension methods already exist. (check out URLHelperExtentions).