Paging/Sorting not working on web grid used in Partial View

后端 未结 1 448
一整个雨季
一整个雨季 2020-12-17 05:49

I have a partial view where I am showing a web grid depending upon a value selected from a page.

For drop down I have used

 @Html.DropDownListFor(
x          


        
相关标签:
1条回答
  • 2020-12-17 06:09

    The following example works fine for me.

    Model:

    public class MyViewModel
    {
        public string Bar { get; set; }
    }
    

    Controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    
        public ActionResult Foo(string value)
        {
            var model = Enumerable.Range(1, 45).Select(x => new MyViewModel
            {
                Bar = "bar " + value + " " + x
            });
            return PartialView(model);
        }
    }
    

    Index.cshtml view:

    <script type="text/javascript">
        $(function () {
            $('#myddl').change(function () {
                var url = $(this).data('url');
                var value = $(this).val();
                $.ajax({
                    url: url,
                    type: 'GET',
                    cache: false,
                    data: { value: value },
                    success: function (result) {
                        $('#result').html(result);
                    }
                });
            });
        });
    </script>
    
    @Html.DropDownList(
        "id",
        new[] {
            new SelectListItem { Value = "val1", Text = "value 1" },
            new SelectListItem { Value = "val2", Text = "value 2" },
            new SelectListItem { Value = "val3", Text = "value 3" },
        },
        new {
            id = "myddl",
            data_url = Url.Action("Foo", "Home")
        }
    )
    
    <div id="result">
        @Html.Action("Foo")
    </div>
    

    Foo.cshtml partial:

    @model IEnumerable<MyViewModel>
    @{
        var grid = new WebGrid(
            canPage: true, 
            rowsPerPage: 10, 
            canSort: true, 
            ajaxUpdateContainerId: "grid"
        );
        grid.Bind(Model, rowCount: Model.Count());
        grid.Pager(WebGridPagerModes.All);
    }
    
    @grid.GetHtml(
        htmlAttributes: new { id = "grid" },
        columns: grid.Columns(
            grid.Column("Bar")
        )
    )
    

    Notice that I have used a GET request to refresh the grid instead of POST because this way the value query string parameter selected in the dropdown is preserved for future sorting and paging.

    0 讨论(0)
提交回复
热议问题