ManInMoon
ManInMoon

Reputation: 7005

How can I put javascript variable into Url.Action

I have a post that work well when I run from VS2015 debug:

        $("#DisplayChartType").bind("change", function () {
            $.post("../Employee/ChangeDisplayChartType", { displayChartType: $("#DisplayChartType").val() }, function (data) {
                iDependOnMyParameter(data);
            })
        });

But post does not work once I have published to IIS. I tried using ../, / and ~/ in the post but none work. I searched web and found the approach below but I still get ARG1 being sent as a parameter instead of my javascript variable.

        $("#DisplayChartType").bind("change", function () {
            $.post("@Html.Action("ChangeDisplayChartType", "Employee", new { displayChartType = "ARG1" })".replace("ARG1",$("#DisplayChartType").val()) , function (data) {
                iDependOnMyParameter(data);
            })
        });

How should I do this? I really would like to stay with $.post approach as that works nicely in VS.

Upvotes: 2

Views: 171

Answers (4)

vrharilal
vrharilal

Reputation: 126

You can try this code.

  $("#DisplayChartType").bind("change", function () {
        var chartType = $("#DisplayChartType").val();
        var url="@Url.Action("ChangeDisplayChartType", "Employee", new { displayChartType = "ARG1" })";
        $.post(url.replace("ARG1", chartType), function (data) {
            iDependOnMyParameter(data);
        })
    });

Upvotes: 1

ManInMoon
ManInMoon

Reputation: 7005

@OJ Raqueno put me on the right path.

At top of script I now declare "myPath". My website URL ends with "secure" so this test gives me the right path:

    var myPath = document.URL;
    if (!myPath.endsWith("secure")) {
        myPath = "";
    }

Then I do this:

    $("#DisplayChartType").bind("change", function () {

        $.post(myPath + "/Employee/ChangeDisplayChartType", { displayChartType: $("#DisplayChartType").val() }, function (data) {
            alert($("#DisplayChartType").val());
            iDependOnMyParameter(data);
        })
    });

Upvotes: 0

OJ Raqueño
OJ Raqueño

Reputation: 4561

You can use window.location.origin or document.location.origin to get the origin of your website, whether running in VS 2015 debug or on IIS.

So instead of doing

$.post("../Employee/ChangeDisplayChartType"

You can try

$.post(document.location.origin + "/Employee/ChangeDisplayChartType"

Upvotes: 0

epascarello
epascarello

Reputation: 207511

So add it to the url

$.post("../Employee/ChangeDisplayChartType?displayChartType=" + encodeURIComponent($("#DisplayChartType").val()), function(){});

or change your original code to GET and the value will be added to the querystring.

Upvotes: 0

Related Questions