Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Load using MVC3 @Url.Action does not pass parameters properly

I noticed that doing @Url.Action("myAction", new { param1 = 123, param2 = 456}) provides me with an invalid URL Home/myAction?param1=123&param2=456.

I am attempting to do

$("#myAjaxDiv").load(url);

But only param1 is getting populated in the action method.

When I remove the & and make it just & then it works, but doing a string replace is super hacky.

url = url.replace("&", "&");

Am I missing something here?

EDIT: Per request I'm including some of my sample app. (you can create a new MVC app and just add these quickly and see for yourself)

Controller:

public ActionResult AjaxTest(int? year, int? month)
{
    ViewBag.Message = string.Format("Year: {0}, Month: {1}", year.HasValue ? year.ToString() : "no year", month.HasValue ? month.ToString() : "no month");
    return PartialView("AjaxTest");
}

AjaxTest View:

@ViewBag.Message

Index View:

<script>
    $(function () {
        var url="";
        $("#noParams").click(function () {
            url = "Home/AjaxTest";
            $("#ajaxy").load(url)
            $("#url").text(url);
        });
        $("#yearParam").click(function () {
            url = "Home/AjaxTest?year=2012";
            $("#ajaxy").load(url)
            $("#url").text(url);
        });
        $("#yearAndMonthParam").click(function () {
            url = "Home/AjaxTest?year=2012&month=10";
            $("#ajaxy").load(url)
            $("#url").text(url);
        });

        $("#generated").click(function () {
            url = "@(Url.Action("AjaxTest", new { year=2012, month=10}))";
            $("#ajaxy").load(url);
            $("#url").text(url);
        });

    });
</script>

<a id="noParams" href="#">No Params</a> <br />
<a id="yearParam" href="#">Year Param</a> <br />
<a id="yearAndMonthParam" href="#">Year and Month Param</a> <br />
<a id="generated" href="#">Generated</a> <br />
<div id="ajaxy">

</div>

<div>
URL: <span  id="url"></span>
</div>
like image 478
Nathan Koop Avatar asked Oct 12 '12 19:10

Nathan Koop


2 Answers

By default every content (which is not IHtmlString) emitted using a @ block is automatically HTML encoded by Razor (see this Razor intro article Html Encoding section)

The Url.Action returns just a plain string so thats why the & gets encoded.

Use the Html.Raw if you don't want the encodeing:

url = "@(Html.Raw(Url.Action("AjaxTest", new { year=2012, month=10})))";
like image 92
nemesv Avatar answered Nov 06 '22 02:11

nemesv


You can build the url in this way also.

var url = "@Url.Action("AjaxTest","YourControllerName")?year=2012&month=10";
$("#ajaxy").load(url);
like image 4
Shyju Avatar answered Nov 06 '22 01:11

Shyju