Gaston Claret
Gaston Claret

Reputation: 998

Webgrid refresh with ajax in MVC3

I have a Webgrid that I need to refresh when pressing a button 'Refresh'. I also have a search input.

Everything is working fine, except that everytime that I hit refresh, the pageNumber is being set back to one...

Here is my code...

controller

public ActionResult ListImporting(string searchText = "", int page = 1)
        {
            ViewBag.RowsPerPage = 2;

            searchText = searchText.Trim();
            ViewBag.searchText = searchText;
            ViewBag.page = page;

            DtoPaginatedResult<ListImportingDTO> model = listService.GetListsInProgress(page, ViewBag.RowsPerPage, searchText);

            if (Request.IsAjaxRequest())
                return PartialView("ListImportingGrid", model);
            else
                return View(model);

        }

Then I have a view List Importing that calls the partial...

<input id="refreshButton" type="button" value="Refresh" style="float:right"/>

<div id="resultList" style="margin-top:20px">
    @Html.Partial("ListImportingGrid", Model)
</div>

......

   $("#refreshButton").live("click",updateGrid);

And inside the partial I have the grid, and the current function

function updateGrid() {     
    var pageNumber = @ViewBag.page;
    console.log(pageNumber);
    $.ajax(
     { type: "GET" ,
         url: '/Admin/ListImporting/',
         data: { searchText: $("#searchBox").val(),  
         page: pageNumber
             } ,
             dataType: "html" ,
             success: function  (data){             
                 $("#resultList").html(data);
                  } 
         })
    }

Upvotes: 1

Views: 6556

Answers (2)

Rob Carroll
Rob Carroll

Reputation: 377

When the page is loaded you are hard coding the pagenumber to ViewBag.page which is always going to be equal to one on page load.

Instead what you need to do is create a hidden input in the partialview and place the javascript code in the main view.

Then when the updateGrid function is triggered look in the patial view, via javascript, and find the value that is in the hidden field for the page number.

Switch to PagedList, it's a lot easier to work with ajax, pagination, and webgrids. https://github.com/TroyGoode/PagedList

Upvotes: 1

bbedward
bbedward

Reputation: 6478

Your pageNumber is being reset back to 1 because every time you call updateGrid you're resetting it to the ViewBag.page

in other words, the compiled razor code looks like

function updateGrid() {
    var pageNumber = 1;
    ....

So you should create pageNumber somewhere else, if you don't want it to be reset when you call updateGrid, like this

var pageNumber = ViewBag.page;
function updateGrid() {
     ....

Upvotes: 0

Related Questions