Lawrence
Lawrence

Reputation: 41

how to avoid postback when i click the button in MVC

I have two button in my cshtml page. When i click the first button data fetch from the database and bind it my controls. The records are many so the second button goes down, then i click the second button same thing happened fetch from the database and bind the grid, so the page is loaded then the page goes up. I want to stay same place when i click the second button. How to prevent it.

Upvotes: 4

Views: 17659

Answers (2)

Jasmine
Jasmine

Reputation: 4029

This is MVC 101...

Make your button a standard HTML5 button, which calls a JavaScript function on click...

 <input type="button" id="goButton" value="Go »" onclick="goFunction();">

(I don't think you have to "return false" with a button, only with a submit)

Then, use Razor helpers in your view to do the Ajax call to the controller...

function goFunction() {
    var url = '@Url.Action("MyActionMethodName", "MyControllerName")';
    var settings = { 'some data': 'some values' };
    $.ajax(url, settings);
}

See the JQuery Ajax page for more information about how to work the "settings" object.

BTW - sounds like you are "paging a grid" but you just forgot to say so... use a tool for that, such as Kendo. Paging is solved, don't solve it again.

Upvotes: 0

Adam
Adam

Reputation: 3914

make your button like this :

<input type="button" id"button2" onclick="CallAjax();return false;"/>

//then in javascript

function CallAjax()
{

//your ajax call here to retrieve or update data

}

Upvotes: 9

Related Questions