AnonyMouse
AnonyMouse

Reputation: 18650

MVC how to call a get from jquery and get the view to display

I created a basic MVC app.

For the home view I made a Create.cshtml page with:

<h2>title Create</h2>

On the home controller I added the get method:

public ActionResult Create(int id)
        {
            return View();
        }

On my Index.cshtml view I have:

@{
    ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">
        http://asp.net/mvc</a>.
</p>
<div class="clicky">click me</div>
<script type="text/javascript">
    $(function () {
        $(".clicky").click(function () {
            $.get('@Url.Action("Create")', { id: "1" }, function () {

            });
        });
    });
</script>

Imagine my surprise when I ran it and found that when click me was clicked the screen didn't change.

I put a breakpoint on Create and found the method was indeed being entered. Also firebug was showing no sign of error.

I then changed the script as follows:

<script type="text/javascript">
        $(function () {
            $(".clicky").click(function () {
                //$.get('@Url.Action("Create")', { id: "1" }, function () {

                //});

                window.location.href = '/Home/Create/1';
            });
        });
    </script>

The app now worked as expected returning the Create view.

Could someone please explain to me why my former method did not work?

Upvotes: 0

Views: 170

Answers (1)

Jan
Jan

Reputation: 16038

Your former method sends an asynchronous request to the server. The returned data (in this case your rendered create view) is passed back into your javascript callback method which is empty in your sample:

$.get('@Url.Action("Create")', { id: "1" }, function (data, textStatus, jqXHR) {

});

Try adding the parameters to your callback funktion and set a javascript breakpoint at the function. You will see, that the html is passed in the data parameter. You could use it to render it in some div or in a dialog like this:

function (data, textStatus, jqXHR) {
    // simply put it in a div
    $("#mydiv").html(data);
    // or open a jquery dialog
    $("#mydiv").html(data).dialog();
});

Or you could use one of the Ajax helpers like Ajax.ActionLink

Upvotes: 3

Related Questions