4

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.

tereško
  • 58,060
  • 25
  • 98
  • 150
Lawrence
  • 41
  • 1
  • 2
  • 7
  • 4
    use `type="button"` with ajax instead of `type="submit"` – Se0ng11 Jul 22 '14 at 06:32
  • you want to stay at same position after clicking on second button (after page load)? if yes then try this http://stackoverflow.com/questions/484463/how-do-i-maintain-scroll-position-in-mvc – Devendra Soni Jul 22 '14 at 06:43
  • thanks for ur reply @Se0ng11, if i use type="button", it can't go to controller. so only I used type="submit". If any possible to go controller when i use type="button".... – Lawrence Jul 22 '14 at 06:44
  • 1
    there is no easy way to make a button to post to server without some code, you need to do some research on AJAX, refer to this post for some idea, http://stackoverflow.com/questions/23604504/asp-net-mvc-passing-json-to-view-from-controller/23605000#23605000, submit button always do a postback(refresh the page) to return the data from server – Se0ng11 Jul 22 '14 at 06:54
  • At the risk of sounding pedantic, there is no "post back" in asp.net mvc, you are talking about a posting to a controller action. – asawyer Jul 22 '14 at 19:54

2 Answers2

9

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

}
Adam
  • 3,815
  • 29
  • 24
0

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.

Jasmine
  • 4,003
  • 2
  • 29
  • 39