Phill Greggan
Phill Greggan

Reputation: 2394

How do i call another view from ajax call?

In the _layout i have a button and i have attached it with click event. the click event calls an action that will return a complete view. what i want to do is load this returning view as a new page to the browser. how to do this?

Upvotes: 0

Views: 1718

Answers (1)

Shyju
Shyju

Reputation: 218722

You can use window.open to open the new page in a new tab/browser window.

$(function(){

  $("#idOfYourLink").click(function(e){
    e.preventDefault();
    var url=$(this).attr("href");
    window.open(url);
  });

});

If it is a button, keep the target url in HTML 5 data attribute.

<button id="btn1" data-url="@Url.Action("MyProfile","Home")">Profile</button>

In the click event read the data attribute

$(function () {
    $("#btn1").click(function (e) {
        e.preventDefault();
        var url = $(this).data("url");
        window.open(url);
    });
})

If you want to update the same page content via ajax without opening a new tab, you can use jQuery load() method to do that. Wrap your @RenderBody method call inside a div.

<div id="pageContent">
    @RenderBody()
</div>
<button id="btn1" data-url="@Url.Action("MyProfile","Home")">Profile</button>

And when the button is clicked, load the new action method's HTML to the pageContent div.

$(function () {
    $("#btn1").click(function (e) {
        e.preventDefault();
        var url = $(this).data("url");
        $("#pageContent").load(url);
    });
})

Upvotes: 1

Related Questions