Monday, 18 September 2017

MVC - Json - How to pass Object (class) from View to Controller using Json (JavaScript) - another example


Watch this example on YouTube


 
1. View
<input type="submit" value="click me" id="btnClick" />

@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnClick").click(function (e) {
                var MyUser = {};
                MyUser.ID = 222;
                MyUser.FName = "FRANK";
                MyUser.LName = "SINATRA";
                MyUser.url = "@Url.Action("TestFunction", "Home")";
                MyUser.type = "POST";
                MyUser.dataType = "json";
                MyUser.data = JSON.stringify({ usr: MyUser });
                MyUser.contentType = "application/json";
                MyUser.success = function (response) {
                    alert("success")
                };
                MyUser.error = function (response) {
                    alert("error")
                };
                $.ajax(MyUser);

            });
        });
    </script>   
}

2. Controller

      [HttpPost]
        public ActionResult TestFunction(User usr)
        {
            return Json(new
            {
                ResultValue = "Some Value"
            });
        }

    }

   public class User
    {
        public int ID { get; set; }
        public string FName { get; set; }
        public string LName { get; set; }
    }
}


1 comment:

  1. Hi there, great tutorial. I copied your project as it is.. TestFunction(User usr) did not have any values in it.

    Are you able to help?

    ReplyDelete