繁体   English   中英

如何创建一个搜索栏,让您搜索数据库中的所有不同字段?

[英]How do you create a search bar that will let you search for all the different fields in your database?

例如,在我的主页/索引页面上,我在数据库中显示信息。 我想创建一个搜索栏,让我搜索与我的搜索匹配的所有值。

例如,数据库有员工,工资和ID。 我选择员工搜索按钮并搜索“Bob”。 搜索将向我显示名为Bob的所有员工。

我现在拥有它,以便我可以从我的HomeController将数据库中的所有内容显示到我的index.cshtml。 我可以做简单的搜索

public ActionResult Index(string employeeName){
//If employeeName, I return employeeName
//else I return something else}

但我不知道如何搜索多个字段并返回它们。 我知道我不能使用重载的ActionResults,所以我尝试使用[ActionName]并使用不同的参数创建不同的Index方法,但搜索不起作用。 我也没有使用ADO.NET实体模型,因为我试图在没有实现实体模型的现有代码中执行此操作。

编辑 - 家庭控制器

public class HomeController : Controller{

    public ActionResult NameSearch(string EmployeeName)
    { //code to display JUST employee's name that matches the Employee variable} 
    public ActionResult SalarySearch(double salary)
    { //code to display JUST employee's sthat matches the salary variable} 
    public ActionResult Index()
    {
      //return View(model); the model has all the data that will be displayed in index.cshtml
    }

index.cshtml-

<h2>Employee</h2>

<form action="/" method="get">
<input type="text" name="EmployeeName" />
<input type="submit" value="Search" />
</form>

<h3>Search Salary</h3>

<form action="/" method="get">
     <input type="text" name="salary" />
    <input type="submit" value="Search" />
</form>

所以有多个搜索框。 如果我在员工搜索中搜索“bob”,我想返回所有匹配的名称。 但我不确定如果我正在这样做,

最终编辑 -

我在Index.cshtml中使用类似的东西完成了这个

<p>

    @using (Html.BeginForm("serialDisplay", "Home", FormMethod.Get))
    {
    <p>
        serial Number: @Html.TextBox("serialNumber") <br />
        <input type="submit" value="Search" />
    </p>
    }
</p>

也许我现在明白这个问题。 您真的更关心Controller方法签名上的参数,而不是如何在控制器中执行内部逻辑,对吗?

您是否知道参数可以默认为null或其他一些合理的值,如果它们没有被传入?

public ActionResult Index( int? id = null, string employeeName = null,double? salary = null){
// if id != null, add it to the where clause.
// if employeeName != null or white space, add it to the where clause (most browsers will send it as "" if the user doesn't enter anything). 
// if salary != null, add it to the where clause, you probably actually want a salaryMin and salaryMax

}

这是处理可选参数的最简单方法,您可以使用自定义模型绑定器执行更多操作。 您还可以使用Routes来根据提供的参数向您发送不同命名的方法。 它还允许您构建事物,以便您可以执行工资和名称。

编辑:MS文档的链接https://msdn.microsoft.com/en-us/library/dd264739.aspx#Optional参数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM