Explain Codes LogoExplain Codes Logo

Url.action parameters?

asp.net
url-action
parameter-encoding
mvc-routing
Nikita BarsukovbyNikita Barsukov·Sep 15, 2024
TLDR

Punch some parameters into ASP.NET MVC's Url.Action using an anonymous object like this:

@Url.Action("Action", "Controller", new { id = 123, name = "John" })

This will give you a hyperlink with the parameters appended as a query string:

<a href="@Url.Action("Action", "Controller", new { id = 123, name = "John" })">Link</a>

Just double-check those parameter names to make sure they line up with your route's expected variables.

Getting serious: Understanding parameter encoding

First things first, to ensure your URLs speak the universal language of the web, parameter encoding has got to be spot on. You can trust the Url.Action method in ASP.NET MVC to do this for you, but it's still a good idea to give your URLs the ol' once-over afterwards - just to be sure that there's no funny business going on.

The importance of matching controller action and parameters

Url.Action parameters need to buddy up with your controller action's parameters. So ensure you're matching the color of your socks (read: types and number of parameters) to your pants (read: controller action). Your action method should look something like this:

public ActionResult GetByList(string category, string subcategory) { // Justice League action here }

And your Url.Action call should correspond to this:

@Url.Action("GetByList", "Products", new { category = "Electronics", subcategory = "Laptops" })

Mind the gap: routeValues object closure

Remember: keep your routeValues object within a close-knit family of curly braces {}. It's just the nice thing to do - and makes sure Url.Action knows what it's dealing with.

<a href="<%: Url.Action("Action", "Controller", new { id = 123, name = "John" }) %>">Link</a>

Default routes are your friends

Pair up with default routes to keep URLs looking nice and tidy. If your action lives in a different area of your MVC application, make sure to include the Area parameter in your Url.Action:

@Url.Action("Action", "Controller", new { Area = "Admin", id = 123, name = "John" })

Say no to spaces (and yes to testing!)

Shun spaces in parameter names like a bad habit. And remember the heavy lifting {} does in MVC syntax these days. Turn on your spider senses and test your hyperlink formation in different web browsers.

Be careful with tricky characters and casing

Do not, I repeat, DO NOT let case sensitivity trip you up in URL generation. Keep a keen eye on the capitalisation of action, controller and parameter names. Avoid enclosing parameter values in string literals, unless you want to play a game of spot the error.