Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with Url.Action helper with multiple route values

I'm currently developing an ASP.NET MVC3 application in VS2010 and I'm having some troubles with @Url.Action helper. I have an ajax request where I use this helper:

var url = '@Url.Action("Action", "Controler", new { a = "a", b = "b" })';
$.post(url).success(function(data) { 
    ... 
});

The problem is that the value of url after this is /Controller/Action?a=a&b=b, note the & between the route values. This isn't working, but if I do:

var url = '@Url.Action("Action", "Controler", new { a = "a", b = "b" })'.replace('amp;', '');

it works perfectly!!!

My action is something like this:

public JsonResult Action(string a, string b) 
{
    ...
}

I have debugged my app and the action gets called and even a is "a", but b is null.

Is this the desired behavior of Url.Action? I don't think so. Please help me, what am I doing wrong? Should I add another parameter to my Url.Action call? Thanks in advance.

like image 970
ecampver Avatar asked Mar 15 '13 03:03

ecampver


1 Answers

The issue here is that when you're using razor syntax: @... the razor engine is encoding the result of Url.Action (which is a string) as an MvcHtmlString. This results in ampersands being encoded as &. To get around this, use Html.Raw (Returns markup that is not HTML encoded.)

var url = '@Html.Raw(Url.Action("Action", "Controller", new { a = "a", b = "b" }))';

Resulting in: '/Controller/Action?a=a&b=b'

Thanks to @GSerg (See comment in Dave Alperovich's answer)... but the desired result isn't javascript encoding. Using HttpUtility.JavaScriptStringEncode("&") results in '\u0026'

like image 193
ngless Avatar answered Sep 25 '22 11:09

ngless