I am attempting to POST data from a React front end to a .NET Core Web API method. I am POSTing using the fetch()
javascript method. When I set a breakpoint in the .NET code to analyze the values of the viewModel, all its members are null.
I've also tried passing a simple string instead of the view model, but that is also null.
I've tried adding the [FromBody]
attribute in front of the parameter.
ContactForm.js
onSubmit(e) {
e.preventDefault();
let data = {
viewModel: {
name: this.state.name,
serviceRequested: this.state.interest,
email: this.state.email,
phone: this.state.phone,
contactPreference: this.state.preference
}
};
fetch('api/Contact/Contact', {
method: POST,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => {
response.text().then(function (text) {
alert(text);
});
});
}
ContactController.cs
private readonly string successMessage = success;
private readonly string modelStateMessage = Invalid input.;
[HttpPost([action])]
public ActionResult Contact(ContactFormViewModel viewModel)
{
if (ModelState.IsValid)
{
}
else
{
return Content(modelStateMessage);
}
return Content(successMessage);
}
ContactFormViewModel.cs
public class ContactFormViewModel {
[Required]
public string Name {get;set;}
public string ServiceRequested {get; set;}
[DataType(DataType.EmailAddress)]
public string Email {get;set;}
[DataType(DataType.PhoneNumber)]
public string Phone {get;set;}
public string ContactPreference {get;set;}
[StringLength(1000)]
public string Message {get;set;}
}
I am expecting the data to populate the view models properties, but they are all null. Firefox's dev tools show the Request is passing JSON params in the body.