^^ Not sure what’s going on here with my theme, that title is feeling a little courageous so let’s just line break a bit and pretend it isn’t overlapping my article…
As well as your typical Html Helpers for ASP.NET MVC in System.Web.Mvc.Html which aids in rendering html for use in your MVC work, have you had a look at the Url Helpers available?
For instance today I had to do a url redirect from JavaScript as my user had two options based on a confirm dialog on what to do, one of which appended a QueryString to the url. So I plugged away at this code:
[sourcecode language='jscript']
top.location.href = ‘/configuration/page/edit/’ + id;
But I did feel a bit uneasy with what I had came up with, basically due simply to the sheer volatility of the thing. What happened if I ever change my action method or controller name for instance? Of course it would break and I'm not really honouring the laws of MVC by approaching my problem this way.
So after recalling the MVC Url namespace but knowing I had not yet looked at it in great detail I found an array of juicy options which could overcome my problem:

Totally awesome! Have a look through those methods ^^. For instance, the one I needed, Url.Action() will allow you to build any MVC url on the fly without decorating it with a hyperlink or so such. So based on my requirements, I simply implemented Url.Action("Edit", new { id = 123 }) and this would output (/record/edit/123); a nice clean url for my purposes which allowed me to remain confident that this was more integral than what I had and would not sucumb to problems if my controller or action name ever changed.
It seems this functionality was glossed over by Scott Gu in this article briefly, but I did want to take you guys into a bit more detail. Plus in case you must have missed it like I did (especially easy to do when you first start getting into MVC and presented with so many new constructs).
2 Comments
Yea i know, i was as happy as you when i first came across this Url.Action()
Oh good one, hadn’t spotted this one yet.
One Trackback/Pingback
[...] Cool Stuff in the System.Web.Mvc.UrlHelper Namespace! [...]
Post a Comment