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

Time:06-17

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'

CodePudding user response:

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

and

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

CodePudding user response:

For default route

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

If you are using custom maproute you need a attribute for route. Like this;

[HttpGet]
[Route("Show/{Id}")]
public async Task<ActionResult> Show(Guid Id)

You can check this https://docs.microsoft.com/tr-tr/aspnet/core/mvc/controllers/routing?view=aspnetcore-6.0

CodePudding user response:

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