4

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?

4
  • Try doing AddEmailPhone([FromBody]EmailPhoneModel Model) Commented Feb 18, 2018 at 17:49
  • @ Hubert Jarema I forgot write I have also tried with [FromBody] Commented Feb 18, 2018 at 17:51
  • Does your EmailPhoneNumber has public getters and setters for Email and Phone? Commented Feb 18, 2018 at 17:58
  • Sure they are all public property. Commented Feb 18, 2018 at 18:00

2 Answers 2

3

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.

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

Comments

0

you can use $.get

//at client side
var url = "apiurl/method1";
var par1="valu";
$.get(url, { contParam1: par1}, function (data)
   {
     //write code here after success 
   } 
    );
//at server side
[HttpGet("method1")]
public ActionResult<IEnumerable<string>> method1([FromQuery(Name = "contParam1")] string contParam1)
            {

            }

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.