绑定WebGrid表单AJAX

时间:2012-07-05 20:10:33

标签: c# json asp.net-mvc-3 razor webgrid

我是MVC3和Razor的新手,一旦从AJAX帖子返回数据,我需要帮助绑定/加载WebGrid。真的很感激任何帮助(项目到期日快速接近);)

我的情况是:我有两个级联下拉列表。第一个列表包含数据库中的区域。选择一个区域后,它会使用一系列设施填充第二个下拉列表。选择设施后,我需要使用建筑物列表填充WebGrid。我有级联下拉正常工作

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>

这是我的AJAX电话

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);
        }

    }
}
);

我的控制器:

[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我建议您进行更改,但我没有看到屏幕上显示任何内容。我也没有任何错误。我逐步完成了代码,并确认视图中的Model对象有12个自定义的“建模模型”对象。

这是我的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. 
    }
}

有趣的是,当我在浏览器中查看视图源时,我看到“此设施中没有建筑物。”但是它没有显示在屏幕上,当我逐步完成代码时,模型确实有我的自定义对象在调试器中。

1 个答案:

答案 0 :(得分:7)

您可以将WebGrid放入部分:

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

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

_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.
    }
}   

现在在你的控制器动作中,如果成功,则返回此部分:

[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 });
    }
}

在您的AJAX调用中只需刷新:

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);
        }
    }
});