使用表格

时间:2016-03-23 14:50:03

标签: c# jquery asp.net-mvc

对于某些输入字段,我需要通过可过滤和可排序的表替换mvc的标准下拉列表,因为有多个列和许多条目可供选择。我添加了局部视图,但现在我通过组合jquery和Razor手动创建表(显示模型数据,然后排序和过滤)也遇到了麻烦。

有人知道这样做的好样本吗?

1 个答案:

答案 0 :(得分:0)

最后我设法创建了一个样本。所以如果其他人正在寻求这个要求的帮助 - 我希望你发现它有用。

需要什么:填写表单时,用户应该能够从汽车列表中选择一个条目。选择显示在带表格的模态对话框中。当用户点击某个条目时,它将写在表单上的字段中。

我正在使用MVC 5.2和Bootstrap 3。

我的测试类Car(型号):

public class Car {
    public Car(long id, string license_plate, string car_type) {
        this.id = id; 
        this.license_plate = license_plate; 
        this.car_type = car_type;
    }
    public long id { set; get; }
    public string license_plate {set; get; }
    public string car_type { set; get; }
}

这里是控制器:

public class HomeController : Controller {
    static List<Car> carList = new List<Car>();

    public ActionResult Index() {
        if (carList.Count() == 0 )
            carList = createCarList();
        return View(new Car(99,"",""));
    }
    // call the modal dialog
    public ActionResult CarSelection() {
        return PartialView("_CarSelection", carList);
    }

    [HttpPost]
    // called by the modal dialog to pass the value the user selected
    public ActionResult CarSelected(int carId) {
        Car theCar = carList.ElementAt(carId);
        return View("Index", theCar);
    }
    // some data entries
    private List<Car> createCarList () {
        carList.Add(new Car(0, "", "Fork Lift"));
        carList.Add(new Car(1, "B-AX 54", "Fordson Power Major"));
        carList.Add(new Car(2, "B-RX 837", "Unimog"));
        carList.Add(new Car(3, "", "Sidelift Crane"));
        carList.Add(new Car(4, "", "Bobcat Excavator"));
        carList.Add(new Car(5, "K-O 38", "Cat Track Loader"));
        carList.Add(new Car(6, "CW-X 2734", "Snowplow"));
        carList.Add(new Car(7, "KI-MR 74", "Toyota Pickup"));
        return carList;
    }
}

在View中是一个输入字段和一个调用模态对话框的按钮:

@model ModalBootstrap.Models.Car

<form class="form-horizontal">
    <div class="form-group">
        @Html.Label("Car", htmlAttributes: new { @class = "control-label    col-sm-2" })
        <div class="col-sm-4">
            @Html.EditorFor(model => model.car_type, new { htmlAttributes =  new { @class = "form-control" } })
        </div>
        <div class="col-sm-6">
            @Html.ActionLink("?", "CarSelection", "Home", null, new { @class = "modal-link btn btn-success" })
        </div>
    </div>
</form>

Bootstrap模式的容器位于_Layout.cshtml:

<div id="modal-container" class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content" style="width:70%; margin:20px auto !important;">
        </div>
    </div>
</div>

<script type="text/javascript">
    $(function () {
        // Initalize modal dialog
        // attach modal-container bootstrap attributes to links with .modal-link class.
        // when a link is clicked with these attributes, bootstrap will display the href content in a modal dialog.
        $('body').on('click', '.modal-link', function (e) {
            e.preventDefault();
            $(this).attr('data-target', '#modal-container');
            $(this).attr('data-toggle', 'modal');
        });
        // Attach listener to .modal-close-btn's so that when the button is pressed the modal dialog disappears
        $('body').on('click', '.modal-close-btn', function () {
            $('#modal-container').modal('hide');
        });
        //clear modal cache, so that new content can be loaded
        $('#modal-container').on('hidden.bs.modal', function () {
            $(this).removeData('bs.modal');
        });
    });
</script>

最后是Partial View _CarSelection.cshtml,用于处理带有数据条目的模态对话框。为了允许过滤和排序,我使用插件DataTables:

@model IEnumerable<ModalBootstrap.Models.Car>

<div class="modal-header">
    <button id="modalButton" type="button" class="close" data-dismiss="modal">&times;</button>
    <h4 class="modal-title">Please Select a Car</h4>
</div>
<div class="modal-body">
    <table id="carsTab" class="table table-striped table-hover" style="width:100%;">
        <thead>
            <tr>
                <th>Id</th>
                <th>License Plate</th>
                <th>Car Type</th>
            </tr>
        </thead>
        <tbody>
            @foreach ( var item in Model ) {
                <tr>
                    <td>@item.id</td>
                    <td>@item.license_plate</td>
                    <td>@item.car_type</td>
                </tr>}
        </tbody>
    </table>
</div>

<form name="carForm" action="/Home/CarSelected" method="post" id="carForm"></form>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<script src="~/Scripts/DataTables/dataTables.bootstrap.min.js"></script>
<link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" />

<script>
    $(document).ready(function () {
        $('#carsTab').dataTable({
            "order": [[ 1, "asc"]],
            "paging": false,
            "ordering": true,
            "scrollY": "450px",  //  table size
            "scrollCollapse": false,
            "columnDefs": [ {
                "targets": [ 0 ], // hide id column
                "visible": false,
                "searchable": false
            }]
        });
        // alignment of table headers
        $('#modal-container').on('shown.bs.modal', function (e) {
            $.fn.dataTable.tables({ visible: true, api: true }).columns.adjust();
        });
        // if user clicks on a row trigger a submit. /Home/CarSelected is called (see <form>)
        $('#carsTab tbody').on('click', 'tr', function () {
            var data = $('#carsTab').DataTable().row(this).data();
            var para = $("<input>").attr("type","hidden").attr("id","carId").attr("name","carId").val(data[0]);
            $('#carForm').append($(para));
            $("#carForm").submit();
        });
    });
</script>