When posting data to Action Method from Ajax Post to Action Method, model is always null. Tried with FromBody and without it, both fails. I am using .NET Core 7.0
My Controller Action Method
[HttpPost]
public async Task<JsonResult> AddOrUpdateAddress([FromBody]AddressViewModel model)
{
var address = _mapper.Map<Address>(model);
My Ajax function
$.ajax({
url: "/Company/AddOrUpdateAddress",
type: "POST",
async: false,
contentType: "application/json;",
data: JSON.stringify(address),
success: function (response) {
company.details.address.addEdit.closeDetails();
$.notify('Saved', { position: "top right", className: "success" });
},
error: function (e) {
$.notify('Error', { position: "top right", className: "error" });
return false;
}
});
Model is as below
public class AddressViewModel
{
public int Id { get; set; }
[Display(Name = "Address Type")]
public int? AddressTypeId { get; set; }
public AddressType? Type { get; set; }
public string? Address1 { get; set; }
public string? Address2 { get; set; }
public string? City { get; set; }
[Display(Name = RegistrationTooltip.State)]
public int? StateId { get; set; }
public string? StateName { get; set; }
[Display(Name = RegistrationTooltip.Country)]
//[DefaultValue(0)]
public int CountryId { get; set; }
[Display(Name = "Zip")]
public string? Zip { get; set; }
public string? FullAddress =>
new Regex("[ ]{2,}", RegexOptions.None).Replace(
$"{Address1?.Humanize(LetterCasing.Title)}, {Address2?.Humanize(LetterCasing.Title)}<br/> {City?.Humanize(LetterCasing.Title)} {(!StateId.HasValue ? StateName?.Humanize(LetterCasing.Title) : State?.Name?.Humanize(LetterCasing.Title))} - {Zip}<br/> <span><img src="/3rdParty/flags/blank.gif" class="flag flag-{Country?.TwoLetterIsoCode}" alt="{Country?.Name?.Humanize(LetterCasing.Title)}"> {Country?.Name?.Humanize(LetterCasing.Title)}</span>",
" ");
public int? CompanyId { get; set; }
[Display(Name = "Is Default")]
public bool IsDefault { get; set; }
[Display(Name = "Primary Hr Contact")]
public string? PrimaryHrContactUserId { get; set; }
[Display(Name = "Primary Finance Contact")]
public string? PrimaryFinanceContactUserId { get; set; }
[Display(Name = "Primary Facility Contact")]
public string? PrimaryFacilityContactUserId { get; set; }
[Display(Name = "Additional Hr Recipients")]
public string? AdditionalHrRecipients { get; set; }
[Display(Name = "Additional Finance Recipients")]
public string? AdditionalFinanceRecipients { get; set; }
[Display(Name = "Additional Facility Recipients")]
public string? AdditionalFacilityRecipients { get; set; }
public State? State { get; set; }
public Country? Country { get; set; }
public List<ShiftViewModel>? Shifts { get; set; }
public List<OperatingHourViewModel>? OperatingHours { get; set; }
public UserLiteDTO ? PrimaryHrContactUser { get; set; }
public UserLiteDTO? PrimaryFinanceContactUser { get; set; }
public UserLiteDTO? PrimaryFacilityContactUser { get; set; }
public bool IsDeleted { get; set; }
}
stringify body messages
{
"CountryId": "2",
"AddressTypeId": "9",
"Address1": "7th Floor, South Wing, ",
"Address2": "Krishe Sapphire",
"Zip": "500081",
"StateId": "92",
"City": "Hyderabad",
"StateName": "",
"Id": "607",
"PrimaryHrContactUserId": "",
"PrimaryFinanceContactUserId": "",
"PrimaryFacilityContactUserId": "",
"IsDefault": false,
"IsDeleted": false,
"OperatingHours": [
{
"Id": 0,
"Day": "Sunday",
"OpeningTime": "",
"ClosingTime": "",
"IsClosed": true,
"CompanyId":1,
"AddressId":1
},
{
"Id": 0,
"Day": "Monday",
"OpeningTime": "11:00 AM",
"ClosingTime": "4:30 PM",
"IsClosed": false,
"CompanyId":1,
"AddressId":1
},
{
"Id": 0,
"Day": "Tuesday",
"OpeningTime": "",
"ClosingTime": "",
"IsClosed": false,
"CompanyId":1,
"AddressId":1
},
{
"Id": 0,
"Day": "Wednesday",
"OpeningTime": "",
"ClosingTime": "",
"IsClosed": false,
"CompanyId":1,
"AddressId":1
},
{
"Id": 0,
"Day": "Thursday",
"OpeningTime": "",
"ClosingTime": "",
"IsClosed": false,
"CompanyId":1,
"AddressId":1
},
{
"Id": 0,
"Day": "Friday",
"OpeningTime": "",
"ClosingTime": "",
"IsClosed": false,
"CompanyId":1,
"AddressId":1
},
{
"Id": 0,
"Day": "Saturday",
"OpeningTime": "",
"ClosingTime": "",
"IsClosed": false,
"CompanyId":1,
"AddressId":1
}
],
"Shifts": [
{
"Id": "0",
"ShiftName": "Regular",
"OpeningTime": "",
"ClosingTime": "",
"IsActive": false,
"CompanyId": 1,
"AddressId":1
},
{
"Id": "0",
"ShiftName": "Morning",
"OpeningTime": "",
"ClosingTime": "",
"IsActive": false,
"CompanyId": 1,
"AddressId":1
},
{
"Id": "0",
"ShiftName": "Night",
"OpeningTime": "",
"ClosingTime": "",
"IsActive": false,
"CompanyId": 1,
"AddressId":1
}
]
}
Here is the sample code base to reproduce the error
https://filetransfer.io/data-package/16ZC8Bck#link
Steps to reproduce
- Run the above code in VisualStudio
- Using PostMan or some other Restful API tool do a HTTPS Post with the payload (request body) shared above as stringify body messages
2
Answers
as @adalyat Nazirov pointed, the issue was with timespan property. I changed the property to string and handled in codebase then post worked.
Your code looks okay, but you have some data inconsistency in your model and payload.
For example, I found that you expect
Id
fields asinteger
, but pass them asstring
. You also have numerous nested models. But the main problem is that in some of your nested moodel you expectedTimeSpan
but passed incorred data or empty string.In my example i used TimeSpan values equal
00:00:00.0000001
Once I fixed that locally, the model can be parsed sucessfully