Filtering a WebGrid with a DropDownList in MVC4

送分小仙女□ 提交于 2019-12-06 15:44:31

$.get("?Customer="+$("#customerDropDown").val()); sends an AJAX call to the server and that's about it. You haven't subscribed to the success callback in order to update your DOM. So it is not surprising that nothing happens.

So try like this:

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

Notice how I have used the UrlHelper to calculate the correct url to your controller action, I have then passed the selected value of the dropdown as second parameter to the $.get method and last but not least I have subscribed to the success callback of the ajax request and updated the #container-grid div with the results returned by the controller action.

Also since you are calling this action with AJAX, you should return only a PartialView from it and not an entire View. This partial view should contain your grid. Otherwise you will end up with duplicate layout injected into the div.

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!