Sending Complex JSON Binding WEBAPI/MVC

In this Example I will show how to pass complex JSON object through nested classes.

Step1:

Create a Model as below.

publicclassAddIncidentModel

    {

        [Required(ErrorMessage = "Company ID can not be blank")]

        publicint CompanyId { get; set; }

 

        [Required(ErrorMessage = "User ID can not be blank")]

        publicint CurrentUserId { get; set; }

        [Required(ErrorMessage = "Password can not be blank")]

        [MaxLength(50)]

        publicstring Password { get; set; }

        [Required(ErrorMessage = "Name can not be blank")]

        [MaxLength(50)]

        publicstring Name { get; set; }

       [MaxLength(500)]

        public string Description { get; set; }

        public int IncidentTypeId { get; set; }

       [MaxLength(250)]

        publicstring IncidentIcon { get; set; }

       [MaxLength(500)]

        publicstring IncidentPlanDoc { get; set; }

        publicAddIncidentActionLst[] AddIncidentActionLst { get; set; }

    }

 

    publicclassAddIncidentActionLst

    {

       publicint SequenceNo { get; set; }

        [MaxLength(250)]

        publicstring ActionDescription { get; set; }

        [MaxLength(500)]

        publicstring ActionPlanDoc { get; set; }   

         publicbool ResponseRequired { get; set; }

         publicint Predecessor { get; set; }

     }

 

Step2:

JQuery Code to Pass To Action Method

var CompId = $("#CompanyId").val();

            var UID = $("#CurrentUserId").val();

            var Pwd = $("#Password").val();

            var NameL = $("#Name").val();

            var DescriptionL = $("#Description").val();

            var IncidentTypeIdL = $("#IncidentTypeId").val();

            var IncidentIconL = $("#IncidentIcon").val();

         

            var customer = {

                CompanyId: CompId,

                CurrentUserId: UID,

                Password: Pwd,

                Name: NameL,

                Description: DescriptionL,

                IncidentTypeId: IncidentTypeIdL,

                IncidentIcon: IncidentIconL,

                AddIncidentActionLst: [{ SequenceNo: 1, ActionDescription: 'Act Desc', ActionPlanDoc: 'ActionPlanDoc',ResponseRequired:false,Predecessor:0 }]

      

            };

 

            $.ajax({

                cache: false,

                url: "http://localhost:2500/api/Incident/AddIncident",

  type: "POST",

                data: JSON.stringify(customer),

                contentType: 'application/json; charset=utf-8',

                success: function (data) { alert('Saved'); },

                error: function () { alert('error'); }

             });