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


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:


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:


Is it possible to specify an action or method on a controller without having to set the parameters?

7/5/2011 10:45:37 AM

Accepted Answer

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.

7/5/2011 12:34:49 PM

Popular Answer

Use T4MVC. This is best option to remove all magic strings and do much more

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