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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With