jqueryajaxasp.net-core-mvc-2.0

JQuery Ajax call not passing parameters to `Controller Method` in ASP.NET Core MVC?


In Ajax call I'm passing a model parameter to the Controller Method but no data is passing to the Controller.

 var Model =
  {
     email: "123",
     phone:"2323"
  };
   $.ajax({
    type: "POST",
    url: `/Home/AddEmailPhone/`,
    data: Model,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        console.log(data);
        console.log(data.length);
    },

    failure: function (data) {
       console.log("failure");
    }, 
    error: function (data) {
        console.log("error");
    }

});

And Controller Method look like

 public JsonResult AddEmailPhone([FromBody]EmailPhoneModel Model)
 {
      Return Json("json");
 }

The ajax call successfully calling the Method but no data is passing.

I also tried to pass value through url like:

 `/Home/AddEmailPhone/email= ${email}&phone=${phone}`

this worked in my another project where I was passing an int value but this time no one is working. what's the wrong I'm doing?


Solution

  • Assuming your model has public properties and url is mapped correctly the only missing bit I see is calling stringify for normalizing your json.

    data: JSON.stringify(Model),
    

    I have tested this with:

    public JsonResult AddEmailPhone(EmailPhoneModel Model)
    {
        return Json("json");
    }
    

    But I don't have Core installed.