【问题标题】:Filtering a WebGrid with a DropDownList in MVC4在 MVC 4 中使用 DropDownList 过滤 WebGrid
【发布时间】:2013-02-23 16:46:21
【问题描述】:

我正在使用 WebGrid,我将其绑定到包含有关交付信息的对象列表。我希望能够使用包含客户的 DropDownList 过滤所述 WebGrid。当我在 DropDownList 中选择一个客户时,更改方法会发送一个 Ajax 调用,该调用应该为 WebGrid 获取新项目。

调用成功,但没有任何反应。 WebGrid 根本没有改变。我什至尝试发送与排序列表时发送的相同的 Ajax 调用。但是什么也没发生。

我在这里做错了什么?

视图模型:

public class DeliveriesViewModel : PageViewModel<DeliveriesPage>
{
    public DeliveriesViewModel(DeliveriesPage currentPage) : base(currentPage)
    {
        DeliveryItems = new List<DeliveryItem>();
    }

    public List<DeliveryItem> DeliveryItems { get; set; }
    public List<SelectListItem> Customers { get; set; } 
}

控制器:

    public ActionResult Index(DeliveriesPage currentPage, string customer)
    {

        var model = new DeliveriesViewModel(currentPage);
        model.Customers = _deliveryService.GetCustomers();
        model.DeliveryItems = customer == null ? _deliveryService.GetDeliveryItems() : _deliveryService.GetDeliveryItems(customer);

        return View(model);
    }

查看:

@model DeliveriesViewModel
<h1>@Model.CurrentPage.PageName</h1>

@Html.DropDownList("customerDropDown", Model.Customers)
@Html.Partial("_grid", Model)
<script type="text/javascript">
    $("#customerDropDown").change(function () {
        $.get("?Customer="+$("#customerDropDown").val());
    });
</script>

_grid局部视图:

@model DeliveriesViewModel
@{
    var grid = new WebGrid(Model.DeliveryItems, canPage:true, canSort: true, ajaxUpdateContainerId:"container-grid");
}

<div id="container-grid">
@grid.GetHtml(
    columns: grid.Columns(
        grid.Column("DeliveryId"),
        grid.Column("CustomerName"),
        grid.Column("ShipNumber"),
        grid.Column("ShipName"),
        grid.Column("Product"),
        grid.Column("PlannedWeight"),
        grid.Column("TotalWeight"),
        grid.Column("ShipStatus"),
        grid.Column("TransportTo"),
        grid.Column("TransportFrom"),
        grid.Column("RevDate"),
        grid.Column("ShipStemDept"),
        grid.Column("ShipRealDept"),
        grid.Column("ShipStemArr"),
        grid.Column("ShipRealArr"),
        grid.Column("TranspMonth"),
        grid.Column("TranspYear")
        ))
</div>

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 webgrid


    【解决方案1】:

    $.get("?Customer="+$("#customerDropDown").val()); 向服务器发送 AJAX 调用,仅此而已。您尚未订阅成功回调来更新您的 DOM。因此,什么都没发生也就不足为奇了。

    所以试试这样:

    <script type="text/javascript">
        $('#customerDropDown').change(function () {
            var url = '@Url.Action("index")';
            $.get(url, { customer: $(this).val() }, function(result) {
                $('#container-grid').html(result);
            });
        });
    </script>
    

    请注意我是如何使用 UrlHelper 计算正确的 url 到您的控制器操作的,然后我将下拉列表的选定值作为第二个参数传递给 $.get 方法,最后但并非最不重要的是我订阅了成功ajax 请求的回调并使用控制器操作返回的结果更新#container-grid div。

    此外,由于您使用 AJAX 调用此操作,因此您应该只返回一个 PartialView 而不是整个 View。此局部视图应包含您的网格。否则,您最终会在 div 中注入重复的布局。

    【讨论】:

    • 当你有一个带有 webgrid 的表单时如何使用它?
    【解决方案2】:
    Model
    
    
     public class EmployerTestResultsModel
        {
    
    
            [Display(Name = "Employer List")]
            public IEnumerable&lt;SelectListItem> EmployerList { get; set; }
    
            [Required]
            public string SelectedEmployerId { get; set; }
    
    
    
            public List<EmployerTestResultsModel> EmployerGrid { get; set; }
    
            public Int64 FileId { get; set; }
    
            [Display(Name = "File Name")]
            public string FileName { get; set; }
    
    
            [DataType(DataType.Date)]
            public DateTime Date { get; set; }
    
    
            [Display(Name = "Scheme Id")]
            public string SchemeId { get; set; }
    
    
            public string Status { get; set; }
    
            [Display(Name = "Validation Error Report")]
            public string ValidationErrorReport { get; set; }
    
    }
    
    
    
    
    controller
    
    
    
    [HttpGet]
            public ActionResult EmployerTestResults()
            {
                EmployerTestResultsModel model = new EmployerTestResultsModel();
    
                ViewBag.HideSection = true;
    
                model.EmployerList = (from d in _context.Employers
                                      select new System.Web.Mvc.SelectListItem
                                      {
                                          Text = d.EmployerName,
                                          Value = d.EmployerId
                                      });
    
    
                model.EmployerGrid = (from efd in _context.EmployerFileDatas
                //                      join efhd in _context.EmployerFileHeaderDetails on efd.FileDataIdentityKey equals efhd.FileDataIdentityKey
                                      orderby efd.EmployerId , efd.Timestamp
                                      select new EmployerTestResultsModel
                                      { 
                                          FileId = efd.FileDataIdentityKey,
                                          FileName = efd.FileName,
                                          Date = efd.Timestamp,
                                          //SchemeId = efhd.SchemeId,
                                          Status = efd.ValidationStatus,
                                          ValidationErrorReport = "View"
    
                                      }).ToList();
    
                return View("EmployerTestResults", model);
            }
    
    
    
    View:
    
    
    @model EFITestHarness.Models.EmployerTestResultsModel
    @using System.Web.Helpers;
    @{
        ViewBag.Title = "EmployerTestResults";
        Layout = "~/Views/Shared/_Layout.cshtml";
    
    }
    
    &lt;script src="~/Scripts/jquery-1.7.1.js">&lt;/script>
    &lt;script src="~/Scripts/jquery.unobtrusive-ajax.js">&lt;/script>
    
    
    @using (Html.BeginForm("EmployerTestResults", "Home", FormMethod.Post, new { @class = "form-horizontal" }))
    {
    
        <div class="text-danger" style="font-size:large;">
            @Html.ValidationSummary(true)
    
        </div>
    
    
    
        <div class="form-group ">
            @Html.LabelFor(s => s.EmployerList, null, new { @class = "col-md-2 control-label" })
            <div class="col-md-3">
                @Html.DropDownListFor(s => s.SelectedEmployerId, Model.EmployerList, "----All----", new { style = "width:250px", id = "ddl", @class = "dropdown1" })
    
                @Html.ValidationMessageFor(s => s.EmployerList, null, new { @class = "text-danger" })
            </div>
        </div>
    
    
        <div id="EmployeeViewGrid">
    
            @Html.Partial("~/Views/EmployerView.cshtml", Model.EmployerGrid)
        </div>
    
    }
    
    &lt;script type="text/javascript">
    
    
                  $('#ddl').change(function (e) {
    
                var employer = $('#ddl').val();           
                $.get('@Url.Action("Filter")', { id: employer }, function (result) {
                    $('#EmployeeViewGrid').html(result);
    
                });
                e.preventDefault();
            });
    
    &lt;/script>
    
    
    
    
    Controller:
    
    
    [HttpGet]
            public ActionResult Filter(string id)
            {
                EmployerTestResultsModel model = new EmployerTestResultsModel();
    
    
                List<EmployerTestResultsModel> objEmployerDetails = new List<EmployerTestResultsModel>();
    
                objEmployerDetails = _repository.getEmployerDetails(id);
    
                model.EmployerGrid = objEmployerDetails;           
    
                return PartialView("~/Views/EmployerView.cshtml", model.EmployerGrid);
    
            }  
    
    
    
    
    
    partial View:
    
    
    @model IEnumerable<EFITestHarness.Models.EmployerTestResultsModel>
    @using System.Web.Helpers;
    @{
        ViewBag.Title = "EmployerTestResultsModel";
        //Layout = "~/Views/Shared/_Layout.cshtml";
    
    
    }
    &lt;script src="~/Scripts/jquery-1.7.1.js">&lt;/script>    
        <div id="gridposition" style="overflow: scroll; height: 300px; overflow-x: hidden;">
            @{
    
                var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridposition"); grid.Pager(WebGridPagerModes.NextPrevious);
    
        @grid.GetHtml(tableStyle: "webGrid",
                    footerStyle: "foot",
                    headerStyle: "webGridHeader",
                    alternatingRowStyle: "webGridAlt",
                    htmlAttributes: new { id = "positionGrid" },
                    selectedRowStyle: "select",
                    fillEmptyRows: true,
                    columns: grid.Columns(
                    grid.Column("FileName"), //the model fields to display
                    grid.Column("Date"),
                    grid.Column("SchemeId"),
                    grid.Column("Status"),
                    grid.Column("ValidationErrorReport", format: (item => Html.ActionLink((string)(@item.ValidationErrorReport).ToString(), "EmployerValidationResults", new { FileId = @item.FileId, @style = "color:blue;" })))
    
    
    
                    ))
            }
    
    
    
        </div>
    

    【讨论】:

    • 大量代码转储,没有任何评论或解释。即使这段代码能满足提问者的要求,它也可能对他没有帮助。
    • @Raidri:我不敢苟同。该代码非常具有解释性,是实现过滤器的一个很好的干净示例。它确实帮助了我!
    猜你喜欢
    • 2013-09-23
    • 2012-03-11
    • 1970-01-01
    • 2015-10-12
    • 1970-01-01
    • 2012-10-18
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多