0

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.

  • The C# code is executed on the server, the JavaScript code is executed on the client. What you want to do is not possible this way. You should explain what your actual goal is so that people can propose a solution. – NineBerry Jul 24 '19 at 15:56
  • See [this](https://stackoverflow.com/questions/8952953/calling-asp-net-mvc-action-methods-from-javascript). I think that will help you. – Ivan Ganchev Jul 24 '19 at 16:04

1 Answers1

0

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 () {
            //...
          }
     });
  }
Andres2142
  • 2,622
  • 2
  • 14
  • 19