I am using ajax to pass Json data to an action in an asp.net core project. I have an array of objects to pass
var AgentScores = [];
.
.
.
AgentScores.push({
AgentId: AgentId,
Fullname: Fullname,
Score : Score
});
$.ajax({
type: "POST",
url: "/Score/SelfReportedScores",
contentType: 'application/json; charset=utf-8',
//large data must be passed using json
data: JSON.stringify(AgentScores),
success: function (result) {
},
error: function (e) {
}
});
I have a class called AgentsListScoreClass.cs and below is how I am trying to get the array in my action:
public void SelfReportedScores([FromBody] List<AgentsListScoreClass> AgentScores)
{
AgentScores
is always null.
It is ok when I pass a List of string, but with AgentsListScoreClass
it is always null.
public class AgentsListScoreClass
{
public string AgentId { get; set; }
public string Fullname { get; set; }
public short Score { get; set; }
}
AgentScores is always null.
Please capture the actual request with posted data in browser developer tool Network tab, and check if the data you posted look like below.
And the property AgentId
of your AgentsListScoreClass
model is defined as string
type, please make sure you wrap the value with quotes, like this "AgentId":"1"
.
Update:
AgentScores.push({AgentId: AgentId, Fullname: Fullname, Score : Score});
this is how data looks like 'data = "[{"AgentId":"015d6fce-2b6e-4702-b4ac-8af31bba8ffa","Fullname":"name","Score":"0"},{"AgentId":" ......'
You can try to use parseFloat()
function to parse Score
data, like below.
AgentScores.push({
AgentId: AgentId,
Fullname: Fullname,
Score: parseFloat(Score)
});