简体   繁体   中英

Creating a Search bar c# MVC

I am trying to create a search bar within my MVC application. I have the following model

    public class Project
{
    public int projectID { get; set; }
    public int customerID { get; set; }
    public int departmentID { get; set; }
    public string projectName { get; set; }
    public int employeeID { get; set; }
}

I want to create a search bar within my index view allowing users to search the list of projects by entering either the projectID or the projectName. So far I have it searching on projectName but I am unsure how (or if it's possible) to search by ID or both at the same time. This is the search bar in my Index view :

   @using (Html.BeginForm())
{
<p>
    Name  : @Html.TextBox("SearchName")<br />
    <input type="submit" value="Search" />
</p>
}

This is my controller method

    public ActionResult Index(string searchName)
    {

        var projects = from pr in db.projects select pr;

        if (!String.IsNullOrEmpty(searchName))
        { 
            projects = projects.Where(c =>  c.projectName.Contains(searchName));
      }

        return View(projects);
      }

Any advice or help would be greatly appreciated! Thanks

Using OR Operators in Where Clauses

You can take advantage of a simply OR || operator to test one or more properties within a single query within the Where() clause :

public ActionResult Index(string searchName)
{
      // Current projects
      var projects = db.Projects;
      // Filter down if necessary
      if(!String.IsNullOrEmpty(searchName))
      {
          projects = projects.Where(p => p.projectName.Contains(searchName) || p.projectName.Contains(searchName));
      }
      // Pass your list out to your view
      return View(projects.ToList());
  }

Handling Different Types

Likewise, if you have multiple properties of different types, you could consider parsing your term if possible and using that :

if(!String.IsNullOrEmpty(searchName))
{
    // Normal search term
    var term = searchName;
    // Attempt to parse it as an integer
    var integerTerm = -1;
    Int32.TryParse(searchName, out integerTerm);
    // Now search for a contains with the term and an equals on the ID
    projects = projects.Where(p => p.projectName.Contains(term) || p.projectId == integerTerm);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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