Bind WebGrid form AJAX

Que picture Que · Jul 5, 2012 · Viewed 19.5k times · Source

I'm a newbie to MVC3 and Razor and I need help on binding/loading a WebGrid once data is returned from AJAX post. Any help would really be appreciated (project due date quickly approaching) ;)

My scenario is this: I have two cascading drop down lists. The first list contains the regions from the database. Once a region is selected it populates the second drop down with a list of facilities. Once a facility is selected I need to populate a WebGrid with a list of buildings. I have the cascading drop downs working correctly

Index.cshtml:

@using ThisController = MyProject.Controllers.BuildingModelsController
@model IEnumerable<MyProject.Models.BuildingModel>

<div id="tabs-2">
    <!-- Current Buildings -->
    @{ 
        if (Model != null && Model.Count() > 0)
        {                            
            var grid = new WebGrid(source: Model, rowsPerPage: ThisController.PageSize, ajaxUpdateContainerId: "tabs-2", defaultSort: "BuildingNumber");
            grid.Bind(Model, rowCount: Model.Count(), autoSortAndPage: false);
            grid.Pager(WebGridPagerModes.All);

            grid.GetHtml(
                tableStyle: "display",
                alternatingRowStyle: "alt",
                columns: grid.Columns(
                //grid.Column(format: (item) => Html.ActionLink("Edit", "Edit", new { EmployeeID = item.EmployeeID, ContactID = item.ContactID })),
                grid.Column("BuildingNumber", header: "Building Number"),
                    grid.Column("ConstructionDate", header: "Construction Date"),
                    grid.Column("ExtSquareFeet", header: "Exterior Sq. Ft."),
                    grid.Column("IntSquareFeet", header: "Interior Sq. Ft."),
                    grid.Column("IU_Avail", header: "IU Available"),
                    grid.Column("SpaceAvail", header: "Space Available"),
                    grid.Column("FixedAssetValue", header: "Fixed Asset Value"),
                    grid.Column("FixedEquipValue", header: "Fixed Equipment Value")
                ));   
        }
        else
        {
            @:There are no buildings at this facility.
        }
     }   
</div>

Here's my AJAX Call

var regId = $("#ddlRegion").val();
var facId = $("#ddlFacility").val();

$.ajax({
    type: "POST",
    url: '@Url.Action("GetFacilityDetails")',
    data: { regionId: regId, facilityId: facId },
    success: function (returndata) {
        if (returndata.ok) {
            var itemData = returndata.data;
            var address = itemData.Address + " " + itemData.City + " " + itemData.State + " " + itemData.Zip;

            $("#lblFacilityType").html(itemData.FacilityType);
            $("#lblFacilityPurpose").html(itemData.FacilityPurpose);
            $("#lblFacilityStatus").html(itemData.FacilityStatus);
            $("#lblFacilityAddress").html(address);

            $("#tabs").tabs({ disabled: [] });
            //need to populate webgrid here
        }
        else {
            window.alert(' error : ' + returndata.message);
        }

    }
}
);

My controller:

[HttpPost]
public ActionResult GetFacilityDetails(int regionId, string facilityId)
{
    try
    {
        //ViewBag.Buildings = buildingsVM.GetFacilityBuildings(regionId, facilityId);
        var facility = buildingsVM.GetFacilityDetails(regionId, facilityId);
        facility.Buildings = buildingsVM.GetFacilityBuildings(regionId, facilityId) as List<BuildingModel>;

        return Json(new { ok = true, data = facility, message = "ok" });
    }
    catch (Exception ex)
    {
        return Json(new { ok = false, message = ex.Message });
    }
}

@Darin I made you suggested changes, but I'm not seeing anything displayed on the screen. I don't get any errors either. I stepped through the code and I confirmed that the Model object in the view has 12 of my custom 'building model' objects.

Here's my PartialView:

@model IEnumerable<COPSPlanningWeb.Models.BuildingModel>
@{ 
    if (Model != null && Model.Count() > 0)
    {
       var grid = new WebGrid(rowsPerPage: 50, defaultSort: "BuildingNumber", ajaxUpdateContainerId: "tabs-2");
       grid.Bind(Model, rowCount: Model.Count(), autoSortAndPage: false);
       grid.Pager(WebGridPagerModes.All);

       grid.GetHtml(
        tableStyle: "display",
        alternatingRowStyle: "alt",
        columns: grid.Columns(
            grid.Column("BuildingNumber"),
            grid.Column("ConstructionDate"),
            grid.Column("ExtSquareFeet"),
            grid.Column("IntSquareFeet"),
            grid.Column("IU_Avail"),
            grid.Column("SpaceAvail"),
            grid.Column("FixedAssetValue"),
            grid.Column("FixedEquipValue")
        ));   
    }
    else 
    {
       @:There are no buildings at this facility. 
    }
}

Interesting thing is when I do a view source in the browser I see "There are no buildings at this facility.", but it's not being displayed on the screen and the Model does have my custom objects when I stepped through the code in the debugger.

Answer

Darin Dimitrov picture Darin Dimitrov · Jul 6, 2012

You could put the WebGrid into a partial:

@using ThisController = MyProject.Controllers.BuildingModelsController
@model IEnumerable<MyProject.Models.BuildingModel>

<div id="tabs-2">
    @Html.Partial("_Buildings")
</div>

And inside _Buildings.cshtml:

<!-- Current Buildings -->
@{ 
    if (Model != null && Model.Count() > 0)
    {                            
        var grid = new WebGrid(source: Model, rowsPerPage: ThisController.PageSize, ajaxUpdateContainerId: "tabs-2", defaultSort: "BuildingNumber");
        grid.Bind(Model, rowCount: Model.Count(), autoSortAndPage: false);
        grid.Pager(WebGridPagerModes.All);

        grid.GetHtml(
            tableStyle: "display",
            alternatingRowStyle: "alt",
            columns: grid.Columns(
                grid.Column("BuildingNumber", header: "Building Number"),
                grid.Column("ConstructionDate", header: "Construction Date"),
                grid.Column("ExtSquareFeet", header: "Exterior Sq. Ft."),
                grid.Column("IntSquareFeet", header: "Interior Sq. Ft."),
                grid.Column("IU_Avail", header: "IU Available"),
                grid.Column("SpaceAvail", header: "Space Available"),
                grid.Column("FixedAssetValue", header: "Fixed Asset Value"),
                grid.Column("FixedEquipValue", header: "Fixed Equipment Value")
            )
        );   
    }
    else
    {
        @:There are no buildings at this facility.
    }
}   

And now inside your controller action in case of success return this partial:

[HttpPost]
public ActionResult GetFacilityDetails(int regionId, string facilityId)
{
    try
    {
        var facility = buildingsVM.GetFacilityDetails(regionId, facilityId);
        facility.Buildings = buildingsVM.GetFacilityBuildings(regionId, facilityId) as List<BuildingModel>;
        return PartialView("_Buildings", facility.Buildings);
    }
    catch (Exception ex)
    {
        return Json(new { ok = false, message = ex.Message });
    }
}

and in your AJAX call simply refresh:

var regId = $("#ddlRegion").val();
var facId = $("#ddlFacility").val();

$.ajax({
    type: "POST",
    url: '@Url.Action("GetFacilityDetails")',
    data: { regionId: regId, facilityId: facId },
    success: function (returndata) {
        if (!returndata.ok) {
            window.alert(' error : ' + returndata.message);
        } else {
            $('#tabs').tabs({ disabled: [] });
            $('#tabs-2').html(returndata);
        }
    }
});