首页 > 解决方案 > 使用多个下拉列表在单个视图中过滤具有两个模型的数据表

问题描述

我开始使用 MVC 创建我的项目,并且非常享受使用 mvc 创建不同的项目。

所以我前段时间创建了数据表,当您在单个下拉列表中选择值时过滤数据

但我仍然对在单个视图中使用多个下拉列表和两个模型过滤数据感到好奇

我做了什么...首先,我创建了一个类,可用于使用两个模型显示我的两个数据表

这是我在 mvc 中的课程

 public class MyData
  {
    public IEnumerable<pmTA_ProjectCategory> ProjectCategory { get; set; }
    public IEnumerable<pmTA_FundCategory> FundCategory { get; set; }
  }

创建我的类后,我为两个数据表创建了一个代码,使用一个视图作为索引和视图用于部分视图来调用两个数据表

这是索引视图和局部视图视图的代码,名称为“MyPartialView”

查看索引:

  @using myProject.Models;
  @model MyData


  <div id="myPartialView">
   @Html.Partial("MyPartialView",Model)
  </div>

  @if (Model.ProjectCategory != null) {
  <table class="table table-bordered table-hover ">
<thead>
    <tr>
        <th>id</th>
        <th>title </th>
        <th>
            description
        </th>

    </tr>
</thead>
<tbody>
    @foreach (var item in Model.ProjectCategory)
    {

        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.id)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.title)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.description)
            </td>

        </tr>
    }
</tbody>
 </table>
}

对于局部视图的视图

      <table id="myDataTable" class="table table-bordered table-hover ">
      <thead>
        <tr>
            <th>id</th>
            <th>code</th>
            <th>
                title
            </th>
            <th>
                description
            </th>
            <th>--</th>
            <th>--</th>
        </tr>
       </thead>
       <tbody>
        @foreach (var item in Model.FundCategory)

        {
            string selectedRow = "";
            if (item.id == ViewBag.fund)
            {
                selectedRow = "success";
            }
            <tr class="@selectedRow">
                <td>
                    @Html.DisplayFor(modelItem => item.id)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.code)
                </td>
                <td>

                    @Html.DisplayFor(modelItem => item.title)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.description)
                </td>
                <td>
                    @Html.ActionLink("Edit", "FundCategoryEdit", new { id = 
          item.id }, new { @class = "btn btn-primary" })
                </td>
                <td>
                    @Html.ActionLink("Select", "Index", new { 
            fund_category_id = item.id }, null)
                </td>
            </tr>
        }
      </tbody>
       </table>

为了运行我的视图,我在控制器中创建了代码以显示两个数据表,我在控制器中声明了我的类的名称

这是我控制器中的代码,第一个代码用于部分视图数据表,第二个代码用于视图索引

对于部分:

      var viewModel = new MyData();
        viewModel.FundCategory = (from p in db.pmTA_FundCategory

                                  select new
                                  {
                                      id = p.id,
                                      code = p.code,
                                      title = p.title,
                                      description = p.description,
                                      status = p.status
                                  }).ToList()
                  .Select(x => new pmTA_FundCategory()
                  {
                      id = x.id,
                      code = x.code,
                      title = x.title,
                      description = x.description,
                      status = x.status
                  });

索引视图

    if (fund_category_id != null)
        {

            ViewBag.fund = fund_category_id.Value;
            viewModel.ProjectCategory = (from p in db.pmTA_ProjectCategory
                          join g in db.pmTA_FundCategory
                           on p.fund_category_id equals g.id
                          where p.fund_category_id == fund_category_id
                          select new
                          {
                              id = p.id,
                              title = p.title,
                              description = p.description,
                              title1 = g.title,
                              status = p.status
                          }).ToList()
               .Select(x => new pmTA_ProjectCategory()
               {
                   id = x.id,
                   title = x.title,
                   description = x.description,
                   title1 = x.title1,
                   status = x.status

               });

        }

        return View(viewModel);

它们一起在索引控制器中,但我将其分开以便您理解我的代码

if 条件的目的是在根据那里的 ID 单击部分数据表的“选择”按钮时显示我的查看索引数据表,您可以使用上面的代码作为参考,以使用其他数据表显示另一个数据表数据表...

为了显示我的多个下拉菜单,我总是使用这个代码

用于显示下拉列表的索引视图代码

     <div>
     @Html.DropDownList("id", ViewBag.funds as SelectList, "Select...", new 
     { @class = "form-control" })
     </div>
     <div>
     @Html.DropDownList("projectcat", ViewBag.proj as SelectList, 
    "Select...", new 
     { @class = "form-control" })
      </div>

控制器中的下拉代码,用于根据数据库数据显示其中的数据

对于第一个和第二个下拉菜单

     var data1 = from p in db.pmTA_FundCategory

                    select new
                    {
                        id = p.id,
                        code = p.code,
                        title = p.title,
                        description = p.description
                    };

        SelectList list = new SelectList(data1, "id", "title");
         ViewBag.funds = list;

     var data2 = from p in db.pmTA_ProjectCategory

                    select new
                    {
                        id = p.id,
                        title = p.title,
                        description = p.description
                    };

        SelectList list1 = new SelectList(data2, "id", "title");
        ViewBag.proj = list1;

问题是......我如何在不使用任何插件的情况下使用多个下拉列表过滤我的部分数据表,但在 javascript 或任何过滤数据表数据的方法的帮助下?

一旦我选择了多个下拉列表的值,我的部分数据表将显示与选择的多个下拉列表相对应的数据...

标签: javascriptc#jqueryasp.net-mvc

解决方案


具有多个下拉列表的多个表

1)在主视图中添加两个下拉菜单,例如

<div class="dropdown">
    @Html.DropDownList("id", (List<SelectListItem>)ViewBag.proj, "--Select id--", new { @onchange = "CallChangefunc1(this.value)" })
</div>

<div class="dropdown">
    @Html.DropDownList("id", (List<SelectListItem>)ViewBag.funds, "--Select id--", new { @onchange = "CallChangefunc2(this.value)" })
</div>

2)添加两个局部视图,第一个带有名称_GetProjectCategory.cshtml,第二个带有名称_GetFundCategory.cshtml

确保

第一个部分视图@model将是类型@model IEnumerable<WebApplicationMVC1.Controllers.ProjectCategory>

第二部分视图@model将是类型@model IEnumerable<WebApplicationMVC1.Controllers.FundCategory>

只需在相应的局部视图中添加您的内容。

确保你的局部视图都包含。

@foreach (var item in Model) { //You table contents }

3)在主视图中调用两个部分视图,例如

<div id="myPartialView1">
    @{Html.RenderPartial("_GetProjectCategory", Model.ProjectCategories);}
</div>

<div id="myPartialView2">
    @{Html.RenderPartial("_GetFundCategory", Model.FundCategories);}
</div>

4)然后创建一个视图模型,如

public class ProjectFundViewModel
{
    public List<ProjectCategory> ProjectCategories { get; set; }
    public List<FundCategory> FundCategories { get; set; }
}

5)您的操作方法将是(其示例代码并替换为您的代码)。

public ActionResult Index()
{
    //The below query replace by yours
    var projects = db.ProjectCategories.ToList();

    List<SelectListItem> dropDownItems1 = projects.Select(c => new SelectListItem { Text = c.title, Value = c.id.ToString() }).ToList();
    ViewBag.proj = dropDownItems1;

    //The below query replace by yours
    var funds = db.FundCategories.ToList();

    List<SelectListItem> dropDownItems2 = funds.Select(c => new SelectListItem { Text = c.title, Value = c.id.ToString() }).ToList();
    ViewBag.funds = dropDownItems2;

    ProjectFundViewModel viewModel = new ProjectFundViewModel
    {
        ProjectCategories = projects,
        FundCategories = funds
    };

    return View(viewModel);
}

6) 将 ajax 调用添加到您在相应下拉菜单中更改任何选项时调用的主视图

<script>

    function CallChangefunc1(id) {
         $.ajax({
             url: "@Url.Action("GetProjectCategory", "Default")",
             data: { id: id },
            type: "Get",
            dataType: "html",    
             success: function (data) {
                 console.log(data);
                //Whatever result you have got from your controller with html partial view replace with a specific html.
                $("#myPartialView1").html( data ); // HTML DOM replace
            }
        });
    }

    function CallChangefunc2(id) {
         $.ajax({
             url: "@Url.Action("GetFundCategory", "Default")",
             data: { id: id },
            type: "Get",
            dataType: "html",    
             success: function (data) {
                 console.log(data);
                //Whatever result you have got from your controller with html partial view replace with a specific html.
                $("#myPartialView2").html( data ); // HTML DOM replace
            }
        });
    }

</script>

7) 最后,您的 ajax 调用在可以呈现相应部分视图的操作方法下方命中。

public PartialViewResult GetProjectCategory(int id)
{
    var projects = db.ProjectCategories.ToList();
    var model = projects.Where(x => x.id == id).ToList();
    return PartialView("_GetProjectCategory", model);
}

public PartialViewResult GetFundCategory(int id)
{
    var funds = db.FundCategories.ToList();
    var model = funds.Where(x => x.id == id).ToList();
    return PartialView("_GetFundCategory", model);
}

8) 确保您的主视图@model不是.@model WebApplicationMVC1.Controllers.ProjectFundViewModelIEnumerable

带有多个下拉菜单的单表

1)在主视图中添加两个带有 id 的下拉菜单

<div class="dropdown">
    @Html.DropDownList("id", (List<SelectListItem>)ViewBag.ids, "--Select id--", new { @onchange = "CallChangefunc1(this.value)", @id = "dropdown1" })
</div>

<div class="dropdown">
    @Html.DropDownList("title", (List<SelectListItem>)ViewBag.titles, "--Select title--", new { @onchange = "CallChangefunc2(this.value)", @id = "dropdown2" })
</div>

2)添加带有名称的局部视图GetFilteredData.cshtmlmodel @model IEnumerable<WebApplicationMVC1.Controllers.ProjectCategory>

确保您的局部视图包含。

@foreach (var item in Model) { //You table contents }

3)在主视图中调用您的局部视图,例如

<div id="myPartialView">
    @{Html.RenderPartial("GetFilteredData", Model.ProjectCategories);}
</div>

4) 现在您的第一个下拉列表包含项目类别ids,第二个下拉列表包含titles项目类别。

public ActionResult Index()
{
    var projects = db.ProjectCategories.ToList();

    List<SelectListItem> dropDownItems1 = projects.Select(c => new SelectListItem { Text = c.id.ToString(), Value = c.id.ToString() }).ToList();
    ViewBag.ids = dropDownItems1;

    List<SelectListItem> dropDownItems2 = projects.Select(c => new SelectListItem { Text = c.title, Value = c.title }).ToList();
    ViewBag.titles = dropDownItems2;

    ProjectFundViewModel viewModel = new ProjectFundViewModel
    {
        ProjectCategories = projects,
    };

    return View(viewModel);
}

5)从主视图添加ajax调用,如

<script>

    function CallChangefunc1(id) {

        var title = $("#dropdown2").val();

         $.ajax({
             url: "@Url.Action("GetFilteredData", "Default2")",
             data: { id: id, title: title },
            type: "Get",
            dataType: "html",
             success: function (data) {
                 console.log(data);
                //Whatever result you have got from your controller with html partial view replace with a specific html.
                 $("#myPartialView").html( data ); // HTML DOM replace
            }
        });
    }

    function CallChangefunc2(title) {

        var id = $("#dropdown1").val();

         $.ajax({
             url: "@Url.Action("GetFilteredData", "Default2")",
             data: { id: id, title: title },
            type: "Get",
            dataType: "html",
             success: function (data) {
                 console.log(data);
                //Whatever result you have got from your controller with html partial view replace with a specific html.
                 $("#myPartialView").html( data ); // HTML DOM replace
            }
        });
    }

</script>

6) 最后,您的 ajax 调用在带有 2 个参数的操作方法下方命中。

public PartialViewResult GetFilteredData(int? id, string title)
{
    var query = db.ProjectCategories.ToList();

    if (id != null)
        query = query.Where(x => x.id == id).ToList();

    if (!string.IsNullOrEmpty(title))
        query = query.Where(x => x.title == title).ToList();

    return PartialView("GetFilteredData", query);
}

推荐阅读