Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile-time checking for action links to controller methods

Tags:

c#

asp.net-mvc

Is there a way to create a strongly typed controller action? For example:

In a Controller I use:

aClientLink = Url.Action("MethodName", "ControllerName", new { Params... });

I would like to use:

aClientLink = Url.Action(Controller.MethodName,ControllerName);

I do not want to re-invent the wheel. I am sure someone has some clever solution. This would allow me to add compile time checking to controller methods.

like image 747
Ross Bush Avatar asked Mar 29 '13 01:03

Ross Bush


1 Answers

You could create your own HtmlHelper extension methods that uses expressions (the same way they are used to reference properties of a model).

@* An expression used to indicate which property of the model should be
examined. It may or may not actually be executed. *@
@Html.IdFor( o => o.FirstName )

@* Don't actually evaluate the expression, just parse it for the method name *@
@Url.ActionFor( o => o.ControllerMethod() )

You can look at the MVC source for examples of helper methods which take expressions as input values, and you can see my answer here for how to retrieve metadata about an object property from an expression.

However...

Used in a view, I would argue that such an approach ties your view far too tightly to the controller. I dislike magic strings but they do provide complete decoupling.

It's not clear if you want to use such methods inside a controller, in which case the separation of concerns becomes less of a problem. You would still lose certain abilities, such as the ability to alias an action name.

like image 156
Tim M. Avatar answered Sep 25 '22 15:09

Tim M.