Monday 7 August 2017

MVC - Json - redirect to acction on success


Watch this tutorial 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.contentType = "application/json";
                f.success = function (response) {
                    alert("SUCCESS");
                    window.location.href = response.Url;
                };
                f.error = function () {
                    alert("FAILED");
                };
                $.ajax(f);
            });
        });
    </script>

Controller

           [HttpPost]
           public ActionResult TestFunction()
        {
            var redirectUrl = new UrlHelper(Request.RequestContext).Action("About", "Home");
            return Json(new { Url = redirectUrl });
        }

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