Using a lambda expression, get the action from the controller. c# expression-trees


I'm attempting to develop a technique that builds a URL based on the names of the controller and action. In lieu of using magic strings, I was considering a method that accepts a lambda expression as an argument.

The tough thing is that I don't want to provide the action method any arguments. Consequently, if I use this controller, for example:

public class HomeController : IController
  public Index(int Id)

The method's name is what I'd want to use:


The formula I came up with has the following signature:

public string CreateUrl<TController>(Expression<Action<TController>> action) where TController : IController

But the issue of skipping the parameters is still present. Only with the specified argument can my method be called:


Is it feasible to declare a controller's action or method without first setting the parameters?

7/5/2011 10:45:37 AM

Accepted Answer

With an expression tree, you cannot ignore the arguments unless your action methods offer optional or default parameters. It is necessary for the expression to be legitimate code, method arguments and all, since expression trees may be turned into runnable code.

Giving a default argument is as easy as in Dan's example below:

public ActionResult Index(int Id = 0)

Additionally, your Expression should be of type because action methods must provide a result. Expression<Func<TController, object>> This will enable the method specified in the phrase to return any kind of object.

Check out MVCContrib without a doubt.

7/5/2011 12:34:49 PM

Popular Answer

Apply zzz-5 zzz. The greatest solution to get rid of all magic strings and accomplish a lot more is this.

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow