Murad Ariff
Murad Ariff

Reputation: 13

jQuery passing value not receiving at the Controller's "Index" Action Method

Question: Why is it that data is not received at the controller action method below? Please let me know what I have missed out in below coding.

My View

    <script src="~/Scripts/jquery-1.5.1.js" type="text/javascript"></script>
    <script type="text/javascript">

    $(document).ready(function () {
    $("#MyLink").click(function () {

        $.ajax({
            type: "POST",
            url: "/Home/Index",
            data: JSON.stringify({ person: {
                                                    id: 11,
                                                    Name: "MyName"
                                                 }
                                    }),
            contentType: "application/json; charset=utf-8"
              });
           });
         });
    </script>

    <a href="#" id="MyLink">Click Here</a>

My Controller

    [HttpPost]
    public ActionResult Index(Person person)
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";

        return View();
    }

My Model

    using System;
    using System.Web;

    namespace MvcApplication1.Models
    {
       public class Person
       {
         int id { get; set; }
         string Name { get; set; }
       }
     }

Upvotes: 1

Views: 95

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

Make the properties on your view model public or the default model binder will ignore them:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Upvotes: 3

Related Questions