Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 924
K.Z Avatar asked Apr 18 '26 09:04

K.Z


1 Answers

Instead of:

JSON.stringify(person)

Do this:

JSON.stringify({ model: person });

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

like image 161
Spencer Ruport Avatar answered Apr 19 '26 23:04

Spencer Ruport