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; }
    }
}


Saturday 16 September 2017

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



watch this example on YouTube


1. View

<input type="submit" value="Click Me" name="btn" id="btnClick" />

@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnClick").click(function (e) {
                var MyUser = {};
                MyUser.ID = 123;
                MyUser.FName = "FRANK";
                MyUser.LName = "ZAPPA";

                $.ajax({
                    url: '@Url.Action("TestFunction", "Home")',
                    type: "POST",
                    data: '{usr: ' + JSON.stringify(MyUser) + '}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        alert("Success");
                    },
                    error: function (xhr, status, error) {
                        alert("Failed");
                    }
                });
            });
        });
    </script>   
}

2. Controller

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

    }

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