Search code examples
c#ajaxasp.net-mvc-4razorwebgrid

Webgrid paging through generic controller method.


I have a generic method to get data for grids in my application, this method gets the data from an API and then returns the predefined grid populated with said data. My problem is that the paging won't work - i.e. nothing happens - when I have used this method.

I thought that it might be down to the URL the paging link is calling - i.e. the generic method - without knowing that other data needs to be sent.

How can I get my webgrid's pagination to work with this generic method?

Generic Method

    /// <summary>Generic grid request method. Used to render any grid with data from a defined location.</summary>
    /// <param name="obj">The data required to complete the operation.</param>
    /// <param name="obj[dataurl]">The URL to be used to get the data for the grid.</param>
    /// <param name="obj[data]">Any data that needs to be sent to the data source when getting the data for the grid.</param>
    /// <param name="obj[gridurl]">The URL for the grid to be rendered.</param>
    /// <returns>The grid populated with data in HTML format.</returns>
    [HandleError]
    [HttpPost]
    public ActionResult GridRequest(string obj)
    {            
        JObject Request;
        string DataUrl, GridUrl, RequestData;
        try
        {
            Request = JObject.Parse(obj);
            DataUrl = (string)Request["dataurl"];
            RequestData = Request["data"] != null ? Request["data"].ToString() : null;
            GridUrl = (string)Request["gridurl"];

            HttpClient client = new HttpClient();
            client.Request.ForceBasicAuth = true;
            client.Request.SetBasicAuthentication(C4SMVCApp.Properties.Settings.Default.APIUsername, C4SMVCApp.Properties.Settings.Default.APIPassword);
            HttpResponse response = client.Post(DataUrl, RequestData, HttpContentTypes.ApplicationJson);
            string result = response.RawText;

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception("Grid Request Error" + result);
            }
            else
            {
                JArray data = JArray.Parse(result);
                return PartialView(GridUrl, data);
            }
        }
        catch (Exception)
        {                
            throw;
        }
    }

Ajax Call

            $.ajax({
                type: "post",
                url: "/C4S/Home/GridRequest",
                data: {
                    obj: JSON.stringify({
                        dataurl: "{0}Community/AANewsApi/AddToList".format(apiBaseUrl),
                        data: new Object({ listId: listId, items: selectedResult }),
                        gridurl: "~/Areas/Comms/Views/Home/Grids/ListPeopleGrid.cshtml"
                    })
                }
            }).done(function (data) {
                $('#persongrid').replaceWith(data);
                $('#addusercontainer').addClass('hidden');
                listGrid();
            }).fail(failCallback);

Webgrid

@model IEnumerable<object>
@{
    WebGrid ListPeopleGrid = new WebGrid(
    source: Model,
    ajaxUpdateContainerId: "persongrid",
    canPage: true,
    rowsPerPage: 16);
}
<div id="persongrid">
@ListPeopleGrid.GetHtml(
    tableStyle: "webgrid",
    headerStyle: "webgrid-header color-2",
    footerStyle: "webgrid-footer color-2",
    rowStyle: "webgrid-row",
    alternatingRowStyle: "webgrid-row",
    fillEmptyRows: true,
    nextText: "Next >",
    previousText: "< Prev",
    columns: ListPeopleGrid.Columns(
    ListPeopleGrid.Column("Id", style: "hidden"),
    ListPeopleGrid.Column("Name"),
    ListPeopleGrid.Column("Manager"),
    ListPeopleGrid.Column("AccessLevel"),
    ListPeopleGrid.Column("Site"),
    ListPeopleGrid.Column("Department")
))
</div>

Solution

  • I found the answer to this here: WebGrid pagination loose parameters with POST data

    I just needed to catch the event and append ?page=[pageNo] to the URL and include the post data in the data: property of the ajax call.