I have a model class as such:
public class DataModel
{
public bool Display { get; set; }
}
I am posting the value from a checkbox after deserializing a FormData object to a JSON object, like this:
this.FormToJSON = form => {
const json = {};
new FormData(form).forEach((value, key) => {
// Ignore the Anti-Forgery Token
if (key !== "__RequestVerificationToken") {
json[key] = value;
}
});
return json;
}
The handler over at the page looks like this:
public IActionResult OnPostSave([FromBody] DataModel model)
{
// Do some stuff
}
The Display property is bound to an input of type checkbox, so when its value of "true" is trying to be deserialized at the Page Handler, this obviously fails and my model parameter ends up being null.
The fix for this would be simple, instead of:
json[key] = value;
I could just write
json[key] = JSON.parse(value);
The only problem is, if I submit a text field that has a value of "true", it gets converted to a boolean, which is obviously not what I want.
Is there a good/better way of doing this? I want to be able to do all my calls in AJAX, because I want to handle the response on the front end i.e if it failed, show a dialog etc. (do not want to use jquery)
2
Answers
I got this to work!
I'm now converting the form into a request like so
And on my page handler, it's been slightly changed to this
Do you want to use
data: $('#idForm').serialize(),
?And remove
[FromBody]
To add below in the pagemodel: