简体   繁体   English

通过 javascript @Url.Action 将数据发送到控制器中的方法

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

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'但在 Show(string data) 的方法中,我在“数据”中有空值

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:假设您可以更改路由以接受路由{controller}/{action}/{id}中的 id,您可以直接发送 id,如下所示:

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

and

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

For default route对于默认路由

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

If you are using custom maproute you need an 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您可以查看此https://docs.microsoft.com/tr-tr/aspnet/core/mvc/controllers/routing?view=aspnetcore-6.0

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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