Search code examples
jqueryajaxasp.net-coreasp.net-core-mvc

Ajax request (Ajax and ASP.NET Core MVC)


I'm trying to send Ajax request to a method, but the request is always null, below is my code.

Ajax request, the request reaches the C# method successfully but always the object is null.

$(document).ready(function () {
    $("#SubmitProduct").click(function () {
        var ProductName = $("#ProductName").val();
        var ProductPrice = $("#ProductPrice").val();
        var Category = $("#Categories").val();
        var Data = { ProductName: ProductName, ProductPricd: ProductPrice, Category: Category };
        //console.log("product name: " + ProductName);
        //console.log("Product Price: " + ProductPrice);
        //console.log("Category : " + Category);
        //console.log("data : " + Data.ProductName);
        //The above log are logging data successfully.
        $.ajax({
            type: "POST",
            url: "/Products/SubmitProduct",
            contentType: "application/json",
            cache: false,
            data: JSON.stringify(Data),
            success: function (data)
            {
                alert("Success");
            },
            error: function (data)
            {
                console.log(data);
            },
            complete: function () {
        
            }

        });
    });
});

The below logs shows the result and it's fine(the parameters have the values as expected).

// console.log("product name: " + ProductName);
// console.log("Product Price: " + ProductPrice);
// console.log("Category : " + Category);
// console.log("data : " + Data.ProductName);

This is the C# method:

[HttpPost]
public async Task <IActionResult> SubmitProduct([FromBody] Products product)
{
    return Content("OK");
}

And this is the Products class:

[Table("Products")]
public class Products
{
    [Key]
    public Guid ProductId { get; set; }

    [Column(TypeName ="varchar(25)")]
    [Required(ErrorMessage ="Product Name is required..")]
    [StringLength(25, MinimumLength = 2, ErrorMessage = "Product name must be between 2 and 25 characters...")]
    public string ProductName { get; set; }

    [Required(ErrorMessage ="ProductName price is required...")]
    [Range(0.001,1000000.000,ErrorMessage = "Price should be between 0.01 and 1000000.000")]
    [Column(TypeName="decimal(10,3)")]
    public decimal ProductPricd { get; set; }

    [Required(ErrorMessage = "Product Image is required...")]
    [NotMapped]
    public IFormFile ProductImage { get; set; }

    [Required(ErrorMessage = "Image Name is required...")]
    [StringLength(50, MinimumLength = 3, ErrorMessage = "Image Name must be between 3 and 50")]
    [Column(TypeName = "varchar(100)")]
    public string ImageName { get; set; }

    [ForeignKey("CategoryId")]
    [Required]
    public ProductsCategories Category { get; set; }

    [ForeignKey("UserId")]
    [Required]
    public string UserId { get; set; }

    // Navigation property
    public ApplicationUsers User { get; set; }

    [Column(TypeName ="varchar(3)")]
    public string IsDeleted { get; set; } = "0";
}

The request reaches the method successfully, but the object is null, any help?

I tried the below ajax, but the object is null too

$.ajax({
    type: "POST",
    url: "/Products/SubmitProduct",
    contentType: "application/json",
    data: JSON.stringify({
        ProductId: "some-guid-value",
        ProductName: "Product Name",
        ProductPrice: 10.99,
        // Other properties here
    }),
    success: function (data) {
        alert("Success");
    },
    error: function (data) {
        console.log("Error: " + data.status + " - " + data.responseText);
    }
});

Solution

  • I reproduced your issue in my side.

    enter image description here

    I'm afraid it related to the model we used, so I create a test model which worked for me.

    enter image description here

    This worked as well.

    enter image description here

    Then I tried this model, you can see we got null once again.

    enter image description here

    In your code snippet, you had var Category = $("#Categories").val(); which looks like Category is a string, but you defined this property as another model. I'm afraid you have to check all of your values set in ajax request.

        [HttpPost]
        public async Task<IActionResult> sendReq([FromBody] Products2 product)
        {
            return Content("OK");
        }
    
    public class Products2 {
        public Guid ProductId { get; set; }
        [Column(TypeName = "varchar(25)")]
        [Required(ErrorMessage = "Product Name is required..")]
        public string ProductName { get; set; }
        public decimal ProductPricd { get; set; }
        [ForeignKey("CategoryId")]
        [Required]
        public string Category { get; set; }
    }
    
    public class Products {
        [Key]
        public Guid ProductId { get; set; }
    
        [Column(TypeName = "varchar(25)")]
        [Required(ErrorMessage = "Product Name is required..")]
        [StringLength(25, MinimumLength = 2, ErrorMessage = "Product name must be between 2 and 25 characters...")]
        public string ProductName { get; set; }
    
        [Required(ErrorMessage = "ProductName price is required...")]
        [Range(0.001, 1000000.000, ErrorMessage = "Price should be between 0.01 and 1000000.000")]
        [Column(TypeName = "decimal(10,3)")]
        public decimal ProductPricd { get; set; }
    
        [Required(ErrorMessage = "Product Image is required...")]
        [NotMapped]
        public IFormFile ProductImage { get; set; }
    
    
        [Required(ErrorMessage = "Image Name is required...")]
        [StringLength(50, MinimumLength = 3, ErrorMessage = "Image Name must be between 3 and 50")]
        [Column(TypeName = "varchar(100)")]
        public string ImageName { get; set; }
    
        [ForeignKey("CategoryId")]
        [Required]
        public ProductsCategories Category { get; set; }
    
    
        [ForeignKey("UserId")]
        [Required]
        public string UserId { get; set; }
    
        // Navigation property
        //public ApplicationUsers User { get; set; }
    
    
        [Column(TypeName = "varchar(3)")]
        public string IsDeleted { get; set; } = "0";
    }
    public class ProductsCategories {
        public int MyProperty { get; set; }
    }
    
    <div id="sendReq">send requyest</div>
    
    @section Scripts{
        <script>
            $("#sendReq").click(function () {
                var ProductName = "prodName";
                var ProductPrice = 15.2;
                var Category = "Categories";
                var Data = { ProductName: ProductName, ProductPricd: ProductPrice, Category: Category };
                $.ajax({
                    url: '/Hello/sendReq',
                    type: 'post',
                    data: JSON.stringify(Data),
                    contentType: "application/json",
                    cache: false,
                    success: function (result) {
                        console.info(result);
                       
                    }
                });
            });