Friday, June 28, 2013

Pass object into to Controller Action Parameter through Jquery Ajax Call in ASP.NET MVC


Consider the below Developer class

Model:

 public class Developer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

    }

In our controller action we accept a developer object.

Controller:

        [HttpPost]
        public ActionResult FirstAjax(Developer developerobj)
        {
            string a = developerobj.FirstName;
            string b = developerobj.LastName;
            return Json(a+" "+b, JsonRequestBehavior.AllowGet);

        }

View:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
         
            var serviceURL = '/MyController/FirstAjax';

            $.ajax({
                type: "POST",
                url: serviceURL,
                data: JSON.stringify({ developerobj: { FirstName: "chamara", LastName: "janaka"} }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: successFunc,
                error: errorFunc
            });

            function successFunc(data, status) {
                alert(data);
            }

            function errorFunc() {
                alert('error');
            }
        });
    </script>

Output:


No comments:
Write comments
Recommended Posts × +