简体   繁体   中英

Use the controller name from Javascript in the Url.Action

I am retrieving controller name from a javascript function as a string, and need to pass controller name in Url.Action. Any suggestion would be helpful.

var controllerName = "MyController";
var id=1;
@Url.Action("LoadAction","'"+ controllerName +"'")?id=' + id
// Here i am unable to pass controllerName, defined using javascript.

Thanks.

If you want to send data from a js script to a C# controller, then you can use a Jquery-ajax call instead of @Url.Action , if I'm not mistaken, you can't even use @Url.Action on a js source code.

const sendId = () => {
    const controllerName = 'MyController';
    const id = 1;
    $.ajax({
          contentType: 'application/json',
          data: { myId: id },
          url: `${controllerName}/methodName`, //template string
          type: 'POST',
          success: function (data) {
             //...
          },
          failed: function () {
            //...
          }
     });
  }

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