Multiple text box search link query

asif ahamed 201 Reputation points
2021-12-13T13:42:29.027+00:00

public ServerContext db = new ServerContext();
public ActionResult Index(FormCollection formCollection, string HostName, string OS)
{
string frmHostName = HostName;
string frmOS = OS;

        ServerContext serverContext = new ServerContext();

       var ServerList = from b in serverContext.Servers
                     where 
                     (string.IsNullOrEmpty(frmHostName)) || (b.HostName.Contains(frmHostName)) && (string.IsNullOrEmpty(frmOS)) || (b.OS.Contains(frmOS))
                     select b;

        return View(ServerList.ToList());


    }

I have 2 text box and try to search and it is not working. If I comment like below it is working for 1 text box search
(string.IsNullOrEmpty(frmHostName)) || (b.HostName.Contains(frmHostName)) //&& (string.IsNullOrEmpty(frmOS)) || (b.OS.Contains(frmOS))
Please help me

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,507 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 54,811 Reputation points
    2021-12-13T16:24:40.483+00:00

    Firstly you should verify that your frmHostName and frmOS variables actually have values. Given your action declaration it doesn't look correct to me but if you could post the URL that is triggering a call to the action that would help.

    For the query itself I prefer to break it up so it is easier to adjust later.

    var query = serverContext.Servers.AsEnumerable();
    if (!String.IsNullOrEmpty(frmHostName))
       query = query.Where(x => x.HostName.Contains(frmHostName);
    if (!String.IsNullOrEmpty(frmOS))
       query = query.Where(x => x.OS.Contains(frmOS);
    
    var servers = query.ToList();
    return View(server);
    

    Your where condition is looking for a contains so if frmOS is win then it would match windows, onewin and onewindow. Make sure that is what you want.

    It isn't clear here but it looks like you're using EF. Therefore also ensure your DB is case insensitive otherwise it won't match the strings either.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.