使用多个下拉列表在单个视图中过滤具有两个模型的数据表 [英] Filtering Data Table with two models in single view using multiple dropdown

查看:89
本文介绍了使用多个下拉列表在单个视图中过滤具有两个模型的数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用MVC创建项目,并且非常高兴使用mvc创建不同的项目.

I started to created my project using MVC and it's really enjoying to create different projects using mvc.

所以我不久前创建了一个数据表,当您在单个下拉列表中选择值时,该数据表会过滤数据

So I created awhile ago the data table that filters data when you selected value in single dropdown

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

But I'm still curious about filtering data using multiple dropdown and two models in a single view

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

What I did... first, I created a class that I can be used to display my two data table using two models

这是我在mvc中的课程

This is my class in mvc

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

创建类后,我使用一个视图用于Index和一个局部视图来调用两个数据表,为两个数据表创建了代码

After creating my class, I created a code for two data table using one view for Index and view for partial view to call the two data table

这是名称为"MyPartialView"的索引视图和部分视图视图的代码.

this is the codes for view of Index and view of Partial View which the name is "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>

为了发挥我的观点,我在控制器中创建了代码以显示两个数据表,我在控制器中声明了我的类的名称

Inorder to Function my view I created codes in controller to display two data table, I declared the name of my class in the controller

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

this the codes in my controller, the first code is for the partial view datatable and the second code is for the View Index

部分:

      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
                  });


查看索引


For View of Index

    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);

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

They are together in the Index controller but I seperated it in order you to understand my codes

如果基于那里的ID单击部分数据表的选择"按钮,则显示if条件的目的是为了显示我的查看索引数据"表,您可以使用上面的代码作为参考来显示其他数据表使用其他数据表...

The purpose of the if condition there is for the displaying of my View Index Data table when click the "Select" button of the partial data table based on there ID, you can use the codes above as your reference for showing another data table using other data table...

为了显示多个下拉菜单,我始终使用此代码

To display my multiple drop down I always used this codes

用于显示下拉菜单的索引视图代码

Codes for View of Index to display dropdowns

     <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>

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

Codes for dropdown in controller to display the data inside of it based on the database data

第一个和第二个下拉列表

for first and second dropdown

     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或任何方法来过滤数据表的数据?

The problem is... How I gonna filter my Partial Data table using multiple drop down without using any plugins but with the help of javascript or any method to filter the data of data table?

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

Once I selected the value of my multiple dropdown my Partial Data table will display the data corresponds to the multiple dropdown selected...

推荐答案

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

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

1) Add two drop down in your main view like

<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

2) Add two partial view 1st with name _GetProjectCategory.cshtml and 2nd with name _GetFundCategory.cshtml

确保

第一个局部视图@model的类型将为@model IEnumerable<WebApplicationMVC1.Controllers.ProjectCategory>

1st partial view @model will be of type @model IEnumerable<WebApplicationMVC1.Controllers.ProjectCategory>

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

2nd partial view @model will be of type @model IEnumerable<WebApplicationMVC1.Controllers.FundCategory>

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

Simply add your content in respective partial view.

确保两个局部视图都包含.

Make sure both of your partial view contains.

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

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

3) Call both partial view in your main view like

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

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

4)然后创建一个类似的视图模型

4) Then create a view model like

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

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

5) Your action method will be (Its sample code and replace by your code).

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调用添加到您在更改相应下拉菜单中的任何选项时调用的主视图中

6) Add ajax call to your main view that called when you change any option in respective drop down

<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调用命中了可以呈现相应局部视图的action方法下方.

7) And finally your ajax call hit below action method that can render respective partial view.

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.ProjectFundViewModel而不是IEnumerable.

8) Make sure your main view @model is @model WebApplicationMVC1.Controllers.ProjectFundViewModel not IEnumerable.

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

1)在主视图中添加两个具有ID的下拉列表

1) Add two drop down in your main view with 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.cshtml且模型为@model IEnumerable<WebApplicationMVC1.Controllers.ProjectCategory>的部分视图.

2) Add partial view with name GetFilteredData.cshtml with model @model IEnumerable<WebApplicationMVC1.Controllers.ProjectCategory>.

确保您的局部视图包含.

Make sure your partial view contains.

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

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

3) Call your partial view in main view like

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

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

4) Now your first drop down contains ids and second drop down contains titles from projects category.

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调用,例如

5) Add ajax call from main view like

<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个参数的操作方法.

6) And finally your ajax call hit below action method with 2 parameters.

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);
}

这篇关于使用多个下拉列表在单个视图中过滤具有两个模型的数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆