【问题标题】:Query Selected Items using checkbox in MVC使用 MVC 中的复选框查询选定项目
【发布时间】:2015-04-30 08:51:31
【问题描述】:

我想问一下,复选框中的选定项目如何用于在 MVC 中进行 linq 查询。 在我的视图中,我显示了所有可能的选项,用户只需选择将用于生成报告的软件类型即可。

@using (Ajax.BeginForm("Create_Report", "Softwares",
            new AjaxOptions
            {
                HttpMethod = "POST",
                InsertionMode = InsertionMode.Replace,
                UpdateTargetId = "target2"
            })) 
        { 
            @Html.ValidationSummary(true)
             <p>For A Reports: Kindly check softwares to create reports.</p><br />
            foreach (var item in Model) { 
                <input type="checkbox" value="@item.software_name" name="software_type"/>@item.software_name
                <br />
            }


            <input type="submit" value="Create Report"/>

        }

之后,我希望在查询中使用所选的软件类型,例如,如果用户选择 Adob​​e Pro、Adobe Illustrator、MS Visio 和 Acrobat,则查询应类似于“从软件 _table 中选择软件__type = "Adobe Pro" && software_type ="Adobe Illustrator && "所以。

是否有任何方法可以使用复选框中的选定项目来缩短查询?非常感谢任何帮助。

【问题讨论】:

  • 您正在发布选定的项目,对吧?然后只显示控制器操作,而不是 html
  • 我是 MVC 的新手。我想问我是否将如何将选定的项目传递给控制器​​。我应该把它放在一个数组中,然后在查询中使用它吗?
  • 显示你发帖的方法——它应该有参数(string[] software_type)
  • 这就是我想问的问题。我仍然对如何在 linq 查询中传递数组感到困惑。

标签: c# asp.net-mvc linq checkbox


【解决方案1】:

假设你的 POST 方法是

[HttpPost]
public ActionResult Create_Report(string[] software_type)

然后software_type 将包含所选值的数组,因此您可以使用.Contains() 过滤查询

var items = db.Software.Where(s => software_type.Contains(s.software_type))

旁注:从您的属性中删除那些糟糕的下划线并遵循正常的命名约定(SoftwareType、SoftwareName 等,或者只是 Type、Name 等,因为它们已经在名为 Software 的类中)

【讨论】:

  • 非常感谢@Stephen。太好了!.. 有效!
【解决方案2】:

您需要定义一个集合来存储您选择的项目并使用模型绑定将所选项目映射到此属性。

//store checked Items
public IEnumerable<string> SelectedSoftware { get; set; }
//check box list items
public List<string> SoftwareList = new List<string>();

 foreach (var item in Model.SoftwareList )
    {
        <input type="checkbox" name="SelectedSoftware" value="@item">@item

    }

在您的控制器中:

public ActionResult Create_Report(string[] SelectedSoftware)
    {
       //do action
    }

【讨论】:

  • 查询过程中会发生什么?
猜你喜欢
  • 1970-01-01
  • 2021-06-28
  • 2019-12-10
  • 2017-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多