Home > Mobile >  Why I getting null Object in controller from Ajax call passing JSON object as data in ASP.NET Core?
Why I getting null Object in controller from Ajax call passing JSON object as data in ASP.NET Core?

Time:02-16

Below code is view page and call Ajax method. I need to pass address object.

var address = {};

address.userId = parseInt($("#userID").val());
address.addressLine1 = $("#addAddressLine1").val();
address.addressLine2 = $("#addAddressLine2").val();
address.cityId = parseInt($("#addAddressCity").val());
address.zipCode = $("#addAddressPostCode").val();
address.mobileNo = $("#addAddressPhoneNumber").val();

$.ajax({
            type: "POST",
            url: "@Url.Action("AddAddress")",
            data:JSON.stringify(address),
            dataType: 'json',
            contentType: 'application/json',
            success: function (responce) {
                if (responce) {
                    alert("true");
                }
                else {
                    alert("fail");
                }
            },
            failure: function (response) {
                alert("failure");
            },
            error: function (response) {
                alert("Something went Wrong");
            }
});

This is the code of my controller action method. I get a Null value of address object when it's called from Ajax:

public IActionResult AddAddress([FromBody] AddressViewModel address)
{
    return Json(address != null);
}

This is my view model:

public class AddressViewModel
{
    [JsonPropertyName("userId")]
    public int UserId { get; set; }
    [JsonPropertyName("addressLine1")]
    public string AddressLine1 { get; set; }
    [JsonPropertyName("addressLine2")]
    public string AddressLine2 { get; set; }
    [JsonPropertyName("zipCode")]
    public string ZipCode { get; set; }
    [JsonPropertyName("mobileNo")]
    public string MobileNo { get; set; }
    [JsonPropertyName("cityId")]
    public int CityId { get; set; }
}

Where do I need to change my code? Do I need to change something in StartUp.cs ?

CodePudding user response:

You need to make sure the value of address.userId = parseInt($("#userID").val()); and address.cityId = parseInt($("#addAddressCity").val());.int type cannot accept null value,if address.userId or address.cityId is null,AddressViewModel address will be null.You can try to use #nullable enable or change the value of address.userId or address.cityId.

#nullable enable
public class AddressViewModel
{
    [JsonPropertyName("userId")]
    public int? UserId { get; set; }
    [JsonPropertyName("addressLine1")]
    public string AddressLine1 { get; set; }
    [JsonPropertyName("addressLine2")]
    public string AddressLine2 { get; set; }
    [JsonPropertyName("zipCode")]
    public string ZipCode { get; set; }
    [JsonPropertyName("mobileNo")]
    public string MobileNo { get; set; }
    [JsonPropertyName("cityId")]
    public int? CityId { get; set; }
}
  • Related