Say i have this ajax to the server:
$.ajax({
type: 'POST',
url: "/Jobs/Sprachen/?handler=RandomNumber",
data: JSON.stringify({ Min: testvariable, Max: "no" }),
contentType: "application/json",
dataType: "json",
}).done(function (data) {
console.log(data);
})
.fail(function (error) {
//nothing for now
});
... and I have this function:
public IActionResult OnPostRandomNumber([FromBody]string input)
{
// called from ajax (no page reload)
return new JsonResult("input: "+input);
}
Why is there always "null" on my input variable?
I wouldve expected a json.
The function it self fires fine and the result is returned and written to the console, but never with anything on the variable
Asp.Net Core achieve model binding via property's name. Here your parameter can't match to the data you send in ajax. You can create a model contains Max
and Min
property, then use this model as parameter.
public class Input
{
//I'm not sure what's the type of Max property, I use string to test.
public string? Max { get; set; }
public string Min { get; set; }
}
Then in the backend
public IActionResult OnPostRandomNumber([FromBody]Input model)
{
// called from ajax (no page reload)
return new JsonResult(model);
}
Now the parameter can receive data successfully