Bicycle Dave
Bicycle Dave

Reputation: 484

CORE 2 MVC Ajax redirect to display a view

I have an application that uses the jQuery Datatable and I want to click on a row, pick up the id, and then bring up a view that allows for editing of that view and updating the underlying database. Ajax gets me to the controller-action that for the edit view but I can't get the view itself to display. Instead, the controller action just returns to ajax. I've tried numerous tactics with no joy. Here is a simple example based upon a standard CORE template:

@section scripts{
    <script>
        $(document).on('click', 'button.number', function () {
            alert($(this).val());
            $.ajax({
                method: 'GET',
                url: '@Url.Action("About", "Home")'
            });
        });
    </script>
}

<h3>Home Page</h3>
<div>
    <button href="#" type="button" class="number" id="one" value="1">1</button>
    <button href="#" type="button" class="number" id="two" value="2">2</button>
</div>

Running the debugger shows that About action is called OK but the view isn't rendered - it just returns to ajax. I've tried all sorts of redirection but any "return" just goes back to ajax.

Is there away around this or perhaps a better way to get from the JS to the controller-action? Thanks

EDIT: Batuhan gets the credit for his solution but I'm re-posting it to clean up a little syntax and add the parameter passing that was my initial goal.

$(document).on('click', 'button.number', function () {
            var id = $(this).val();
            alert(id);
            $.ajax
                ({
                    method: 'GET',
                    url: '@Url.Action("About", "Home")',
                }).success(function (result) {
                    window.location.href = '/home/about/' + id;
                });
        });

And here is Home Controller for the About Action:

public IActionResult About(int id)
        {
            string parm2 = id.ToString();
            ViewBag.msg = parm2;
            return View();
        }

And the About page:

@{
    ViewData["Title"] = "About";
}
<p>
    <h1> @ViewBag.msg </h1>
</p>

All works as initially hoped for!

Upvotes: 1

Views: 2123

Answers (1)

Batuhan Kara
Batuhan Kara

Reputation: 304

 $(document).on('click', 'button.number', function () {
            alert($(this).val());
            $.ajax({
                method: 'GET',
                url: '@Url.Action("About", "Home")'
            }).success: function(result){
       ///this line 
window.href='redirect url';

    }});;
        });

this is a solution cause you cant redirect from ajax call. it returns The view in html form So if you want to postback you needto use window.href="url";

Upvotes: 1

Related Questions