Creating non-variable querystrings using action link helpers

Intro

This post is more kind of tip. The action link html helpers really simplifies our job in generating hyperlinks. These html helpers are integrated with the routing infrastructure and that helps to generate links very smartly. There are lot of overloaded versions available but most of them takes the route values as an anonymous object.

@Html.ActionLink
(
	"Purchase Product",  					 // link text
	"Purchase",  									 // action name
	new { userName = Model.User  } // route values as an anonymous object
)

Sometimes the parameters that needs to be passed to the action don’t need to be in routes but instead they have to be in query-strings.

An example,

http://mapservices.com/location/show?lat=12.12&lon=23.5

In these cases also the built-in action link extensions works just fine because still we can pass the lat and lon querystring variables wrapped in an anonymous object new { lat = 12.2, lon = 23.5 }.

Suppose we need to generate an URL like below,

http://mapservices.com/location/show?pos.lat=12.12&pos.lon=23.5

The querystring names contains a "." operator and when you use an anonymous object to pass these values as new { pos.lat = 12.12, pos.lon = 23.5 } you will run into an exception.

RouteValueDictionary

The route values we pass as anonymous object are convereted into RouteValueDictionary. There are overloaded action link helpers available that directly accepts RouteValueDictionary as parameter. As a dictionary we can easily pass querystrings that contains "." as below,

@Html.ActionLink
(
	"Show the location", 
	"Show", 
	"Location", 
	new RouteValueDictionary{{"pos.lat", 12.12}, {"pos.lon", 23.5}}, 
	null
)
blog comments powered by Disqus