Get action from controller using lambda expression

I am trying to create a method that creates a url based on controllername and actionname. I don't want to use magic strings, so I was thinking of a method that takes a lambda expression as a parameter.

The hard part is that I don’t want to specify any parameters in the action method. So, for example, if I have this controller:

public class HomeController : IController { public Index(int Id) { .. } } 

I would like to call the method as follows:

 CreateUrl<HomeController>(x=>x.Index); 

The signature of the method I came up with is:

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

But this does not solve the problem of missing parameters. My method can only be called using the parameter specified as follows:

 CreateUrl<HomeController>(x=>x.Index(1)); 

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

+4
source share
3 answers

It is not possible to omit parameters using the expression tree unless you have optional or standard parameters in your action methods. Since expression trees can be compiled into executable code, the expression is still checked by the compiler, so it should be a valid parameter of the code method and that’s it.

As in the example below, submitting a default parameter is as simple as:

public ActionResult Index(int Id = 0)

In addition, since action methods must return some kind of result, your expression must be of type Expression<Func<TController, object>> , which will allow you to return any type of object from the method defined in the expression.

Definitely check out MVCContrib .

+4
source

Use T4MVC . This is the best way to remove all magic lines and do much more.

+3
source

As bdowden said, you should specify parameters or default values ​​for parameters as such:

 public class HomeController : IController { public Index(int Id = 0) { .. } } 

Also, if you use MVCContrib , these extension methods already exist. (check URLHelperExtentions).

+1
source

All Articles