Using AJAX, I am sending a model to the server via a POST request.
I have defined a model and a controller method for processing it.
public class TestDto: BaseDto
{
[Required]
public ProductGalleryDto GalleryProduct { get; set; }
public int? RetailPriceEur { get; set; }
[Required]
public int? AmountSpc { get; set; }
public bool? PrizeSent { get; set; }
public string Comment { get; set; }
public DateTime? StartDate { get; set; }
[Required]
public DateTime? ExpirationDate { get; set; }
public bool IsParticipant { get; internal set; }
}
public override IActionResult Post([FromBody] TestDto item)
{
if (!IsAdmin)
return BadRequest(ApiErrorCodes.InsufficientPriveleges);
if (!ModelState.IsValid)
return BadRequest(ApiErrorCodes.RequiredFieldsMissing, ModelState.Keys.FirstOrDefault());
}
JavaScript (JS):
var object = JSON.stringify({
createddate: startdate,
retailpriceeur: price,
amountspc: spobicoinprice,
prizesent: false,
expirationdate: expirationdate,
comment: comment,
productgalleryid: productgalleryDto
});
$.ajax({
headers: { "Authorization": "Bearer " + localStorage.getItem('authToken') },
url: "/api/testapi/",
method: "post",
data: object,
contentType: "application/json; charset=utf-8",
success: function (result) {
}
});
The fields in JS must match those in the model. When the model is not valid, how can I fix this? Any assistance would be greatly appreciated.