简体   繁体   中英

How to pass the action and controller to the @Url.action call

I would like to pass the action name and controller name to the @Url.action call within a Javascript function as variables. Is there a method to achieve this?

function list_onSelectionChanged(e) {
    var strActionName = "Map";
    var strControllerName = "PMO";
    $("#content").load("@Url.Action(strActionName,strControllerName)");
}

You can't pass them from client-side code in this way because the server-side code has already run at that point. Specify them directly in the server-side operation:

function list_onSelectionChanged(e) {
  $("#content").load("@Url.Action("Map", "PMO")");
}

Note that it looks like the syntax will fail because of nested double-quotes. However, keep in mind that the Razor parser identifies the server-side code separately from the client-side code. So this is the entire server-side operation:

Url.Action("Map", "PMO")

And the result of that operation is emitted to the client-side code:

$("#content").load("result_of_server_side_operation");

I was able to modify the script as follows:

function list_onSelectionChanged(e) {
    var url = e.addedItems[0].path;
    $.get(url, function (data) {
        $("#content").html(data);
    });
}

Even simpler:

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

This allows a variable to be passed for the url.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM