K.Z
K.Z

Reputation: 5075

Can't read $ .ajax data in controller

I am trying to create a jQuery .ajax program in which the user clicks button in view, which triggers to $.ajax followed by send name to controller where controller add hello in front of name and send back json response.

I have managed to receive JSON response from controller, but failed to read post data name in controller.

Here is my code:

controller class

    public JsonResult processJsonRequest(PersonModel model)
    {       
        string returnString = "Hello , receive JSON data" + model.Name;
        return Json(returnString, JsonRequestBehavior.AllowGet);
    }

Model class

public class PersonModel
{
    public string Name { get; set; }
}

View

@{
ViewBag.Title = "Index";}

 @Scripts.Render("~/bundles/jquery")

 @using (Html.BeginForm())
   {
      <input type="button" id="b1" value ="Press Me" />  
   }

 <script type="text/javascript">

   $(document).ready(function () {

    $("#b1").click(function () {

        var person = { Name: 'khurram' };

        $.ajax({
            type: "POST",

            url: "/JSON_Ajax_03/processJsonRequest",
            data: JSON.stringify(person),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (response) {
                alert(response);
            }
        });
    });
});

</script>

Upvotes: 3

Views: 1230

Answers (1)

Spencer Ruport
Spencer Ruport

Reputation: 35117

Instead of:

JSON.stringify(person)

Do this:

JSON.stringify({ model: person });

The problem is you aren't naming the model parameter correctly.

Upvotes: 4

Related Questions