send data to method in controller by javascript @Url.Action

Viewed 82

Hi i try send data to method in controller

 var data = {
  Id: e.row.key.Id
 }
       
 window.location.href = '@Url.Action("Show", "Calculations", new {param1 =  data})';
  //here in javascript I have error, near 'data'

error

the name 'data' does not exist in current context

Controller

[HttpGet]
    public async Task<ActionResult> Show(string data)

I tried

     window.location.href = '@Url.Action("Show", "Calculations")' +"/"+ data;  

but in method in Show(string data) i have null value in 'data'

3 Answers

Assuming you'd be able to change to route to accept the id in the route {controller}/{action}/{id}, you could just send the id directly, as follows:

 window.location.href = '@Url.Action("Show", "Calculations")/' + e.row.key.Id; 

and

[HttpGet]
    public async Task<ActionResult> Show(Guid Id)

As you have parameter name = data at controller level, try below

var dataObj = {
  Id: e.row.key.Id
 }
       
 window.location.href = '@Url.Action("Show", "Calculations", new {data = dataObj})';

You were missing parameter name in Url.Action. this name has to match as is at both controller and in script file.
Related