How to refresh mvc webgrid

itzmebibin picture itzmebibin · Mar 9, 2016 · Viewed 9.9k times · Source

I am using a WebGrid in my mvc application.

<div class="grid-div" id="webgridid">
                @grid.GetHtml(
    tableStyle: "gridTable",
    headerStyle: "gridHead",
    footerStyle: "gridFooter",
    columns: new[]
    {
        grid.Column("name","Name", canSort: true, style: "name"),
        grid.Column("description","Description", canSort: true, style: "description"),
        grid.Column("duration","Duration", canSort: true, style: "duration"),
   })
</div>

I can edit the selected row values using a form. After editing this values, it is not reflecting in my webGrid. But it is reflecting in DataBase. To reflect this in to the webGrid, I need to refresh the webGrid by loading datas from DB. How can I reload contents to webGrid from DB? Also after reloading it, this pageNumber should the old one. How to do this?

Answer

itzmebibin picture itzmebibin · Mar 9, 2016

Finally I find the solution for my problem. I have to define a <div> with ID and refer the div’s id in the ajaxUpdateContainerId attribute of WebGrid control that will allow WebGrid to update data asynchronously using Ajax.

<div id="ajaxgrid">
  @{
      var grid = new WebGrid(Model, rowsPerPage: 10, selectionFieldName: "SelectedRow", ajaxUpdateContainerId: "ajaxgrid");                   
   }
</div>

Then, call the GetHtml method of WebGrid, so that Razor Engine can generate corresponding HTML for it. After the end of <div> tag.

@grid.GetHtml(
    tableStyle: "gridTable",
    headerStyle: "gridHead",
    footerStyle: "gridFooter",
    columns: new[]
    {
        grid.Column("name","Name", canSort: true, style: "name"),
        grid.Column("description","Description", canSort: true, style: "description"),
        grid.Column("duration","Duration", canSort: true, style: "duration"),
   })

Then in my ajax call for updation I have added location.reload() to refresh my WebGrid.

$.ajax({
                url: '@Url.Action("User", "UserDetails")',
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: formData,
                contentType: false,
                processData: false,
                success: function (result) {
                    if (result == "OK") {
                        location.reload();
                    }
                    else
                        alert(result);
                },
                error: function (result) {
                    alert('Error!');
                }
            });

Now its working fine for me.