I would like to pass array values from javascript to my C#.
Currently I am getting GUID
null in C#. Not sure where I am doing wrong.
When I check developer tool, I have values
http://localhost/mvc/CheckData?GUID[]=C71F952E-ED74-4138-8061-4B50B9EF6463&ColumnVal=1&RowVal=1
I would like to receive this GUID
value in my C# code.
JavaScript
function CheckData(obj) {
$.ajax({
data: {GUID:eArray, ColumnVal: $('#DisColumn').val(), RowVal: $('#DisRow').val()},
url: "/mvc/CheckData",
cache: false,
success: function (result) {
....
}
});
}
C# backend code to receive values from front-end.
public ActionResult CheckData()
{
var GUID = HttpContext.Request["GUID"];
int columnVal = Convert.ToInt32(HttpContext.Request["ColumnVal"]);
int rowVal = Convert.ToInt32(HttpContext.Request["RowVal"]);
string result = (Services.CheckDataRecords(rowVal, columnVal,GUID)) ? "true" : "false";
return Content(result);
}
Currently, I am getting null
when it hits to C# method var GUID = HttpContext.Request["GUID"];
.
I can see array value in front-end. But it is somehow not passing that value.
CodePudding user response:
The problem is that you are not sending the data correctly in your JavaScript code. When you send an array in the data property of the $.ajax() method, it will be converted to a query string format like this: key[]=value1&key[]=value2&key[]=value3
However, in your C# code, you are trying to access the value by using the key "GUID" as if it's a single value, not an array. To fix this, you can try changing the way you access the value in your C# code to:
var GUID = HttpContext.Request.Query["GUID"].ToArray();
This will convert the query string value to an array of strings in C#, and you can then pass that array to your Services.
Alternatively, you can change the way you are sending the data in your JavaScript code to include the square brackets in the key:
data: {'GUID[]':eArray, ColumnVal: $('#DisColumn').val(), RowVal: $('#DisRow').val()}
This way, the key in the query string will match the key you are using to access the value in your C# code.
CodePudding user response:
HttpContext.Request
represents the request, and to access query data, you will need to do something like this: HttpContext.Request.Query["GUID"]
.
A more straightforward approach is to let ASP.NET do the work for you is just turn your C# backend to this:
[HttpGet("CheckData")] //change the route based on your code
public ActionResult CheckData([FromQuery] Guid[] guid, int columnVal, int rowVal)
{
var GUIDs = guid;
int column = columnVal;
int row = rowVal;
.....//your code
}