无法发送带有 @ViewData[“Param”] 的参数

Can't send parameter with @ViewData["Param"]

提问人:Fajar Pratama 提问时间:2/16/2023 更新时间:2/16/2023 访问量:50

问:

我需要帮助,我无法将参数从 javascript 中的 ViewData 发送到控制器,可能是因为在控制器中使用 JsonResult,但到目前为止我还没有找到解决方案,有什么方法可以解决它吗?

这是我的JS:

var urlString2 = "@Url.Action("GetAttributeLabel", "MasterDataTemp")?modifierId=@ViewData["ModifierId"]";
$.ajax({
   url: urlString2,
   type: "GET",
   dataType: "json",
   contentType: 'application/json; charset=utf-8',
        async: true,
        processData: false,
        cache: false,
        success: function (data) {
     $.each(data, function (i, item) {
        dataAttributeLabel.push(item.AttributeName);
    });
   },
    error: function (xhr) {
       alert('error');
   }
});

这是我的控制器:

public JsonResult GetAttributeLabel(Guid modifierId)
{
...........
}

参数始终发送空 guid,请帮忙。

JavaScript asp.net ajax asp.net-core jsonresult

评论


答:

0赞 sina_Islam 2/16/2023 #1

请尝试如下

@{
 string guid = ViewData["ModifierId"].ToString();
}
var urlString2 = "MasterDataTemp/GetAttributeLabel?modifierId="+"@guid";

$.ajax({
   url: urlString2,
   type: "GET",
   dataType: "json",
   success: function (data) {
     $.each(data, function (i, item) {
        dataAttributeLabel.push(item.AttributeName);
    });
   },
    error: function (xhr) {
       alert('error');
   }
});

在控制器上

public JsonResult GetAttributeLabel(string modifierId)
{
...........
}

评论

0赞 Fajar Pratama 2/16/2023
@sina-islam返回值发送,我只需要guid值{ ModifierId = 634715fc-1c51-4f02-87ef-826fcefb877e }
0赞 sina_Islam 2/16/2023
它应该按照测试工作。
0赞 Fajar Pratama 2/16/2023
感谢您的帮助,现在代码工作正常
0赞 Ruikai Feng 2/16/2023 #2

首先,您必须避免使用 jQuery Ajax 请求发送 JSON 数据,如果您确实想发送 JSON 数据,请尝试使用请求。GETPOST

其次,您可以像这样生成 url:@Section

@{        
    string val = ViewData["key"] != null ? ViewData["key"].ToString()
                                         : "defaultval"; 
       
    var routedic = new Dictionary<string, string>()
                       {
                           { "key", val }
                       }; 
       
    var url = Url.Action("Test", "Home", routedic);
} 

然后发送请求:

<script>    
  var urlstr="@(url)";
  // check the uri in console  
  console.log(urlstr);   
 $.ajax({       
   url:urlstr,        
   type:"GET"    
});
</script>

它现在运行良好:

enter image description here

评论

0赞 Fajar Pratama 2/16/2023
感谢您的回复,这是另一种方式,我尝试使用我的代码并工作