1

I am trying to post a javascript object, representative of a Model, back to a controller using an ajax post. However, the model is always showing as null.

The model in question is as follows

public class Product
{
    [Key]
    public int Id { get; set; }

    [Required(ErrorMessage = "Name is required and must not be empty.")]
    [StringLength(200, ErrorMessage = "Name should not exceed 200 characters.")]
    public string Name { get; set; }

    public DateTime Created { get; set; }

    [Required(ErrorMessage = "Price is required and must not be empty.")]
    [DataType(DataType.Currency)]
    public decimal Price { get; set; }
}

With the ajax call looking like so

$('#btnSaveNewProduct').click(function (e) {
                e.preventDefault();
                var form = $('#frmNewProduct');
                if (form.valid()) {
                    var data = { // to be replaced with form values
                        Name: 'Bob',
                        Price: 34
                    };
                    //ajax call to save product
                    $.ajax({
                        type: "POST",
                        url: "@Url.Action("AddProduct", "Admin")",
                        contentType: "application/json",
                        dataType: "json",
                        data: data,
                        success: function (response) {
                            alert('done');
                        },
                        error: function (response) {
                            alert(response);
                        }
                    });
                }
            });

The controller method looks like the following

    [HttpPost]
    public JsonResult AddProduct([FromBody] Product product)
    {
        bool success = false;
        // save product
        success = true;
        return new JsonResult(success);
    }

Any insight would be most appreciated.

12
  • 3
    data: "json", data: data? Commented Oct 17, 2018 at 22:19
  • 4
    data: "json" -> 'dataType: "json"` Commented Oct 17, 2018 at 22:21
  • 1
    I also suggest you look into AJAX Helpers. Here is a C# Corner post about them: https://www.c-sharpcorner.com/article/Asp-Net-mvc-ajax-helper/. Commented Oct 17, 2018 at 22:48
  • 1
    @CodeBreaker Those are deprecated in ASP.NET Core Commented Oct 17, 2018 at 23:14
  • 3
    try data: JSON.stringify(data), Commented Oct 18, 2018 at 6:21

2 Answers 2

1

To get your code to work as desired, make the following three modifications to your code.

  • From the Ajax call, remove this: dataType: "json"
  • From the Ajax call, remove this: data:data
  • In the Ajax call, add this: data:JSON.stringify(data)

IMPORTANT POINTS TO NOTE:

  1. When you are using the [FromBody] attribute, the Content-Type value determines the formatter for the ASP.NET Core MVC Framework to use for parameter binding.

  2. Since your Content-Type is application/json, a raw JSON string and not a JSON object, should be passed as data. Hence, apply JSON.stringify.

  3. See this reference: Parameter Binding Using [FromBody] Attribute

Sign up to request clarification or add additional context in comments.

Comments

0

I found below working:

    $.ajax({
        method: "POST",
        data: { "Name": "bob", "Price": 10},
        url: "@Url.Action("AddProduct", "Admin")",
        success: function (data) {
            //success login
        },
        error: function (data) {
            alert('error' + data.status);
        }
    });

no need to mention dataType and contentType in ajax call. And your controller will like below:

[HttpPost]
public ActionResult AddProduct(Product product)
{
    //You logic will be here
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.