Monday, 7 August 2017

MVC - How to pass multiple values from JavaScript (Json) to Controller

Watch this example on YouTube



View

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

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

    </script>   
}

Controller

        public JsonResult TestFunction(int ID, string FName, string LName)
        {
            return Json(new
            {
                resut = "OK"
            });
        }

3 comments:

  1. GOD BLESS YOU MAN .... THATS GREAT..THANKYOU

    ReplyDelete
  2. This is so awesome, THANK YOU SO MUCH, this is a REAL SOLUTION for a (so called) SIMPLE issue. A GREAT SOLUTION for NON-C# (Razor) programmers to be able to get a variable(s) back AND ACTUAL use them easily.

    ReplyDelete
  3. i have one issue like this , i have json file in controler then how to i call my json file in javascript

    ReplyDelete