Multiple text box search link query

asif ahamed 201 Reputation points

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

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

Accepted answer
  1. Michael Taylor 44,231 Reputation points

    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