Search code examples
webmatrixrazorengine

If search don't return values from database show an empty form


So i got a page that have a search form, and when the user search for a value if there are no records on database the form returns empty, but if there are records the form is populated with data.

What i was thinking was this

    var db = Database.Open("myDataBase");
    var selectCommand = "SELECT * FROM exportClient";
    var searchTerm = "";

    if(!Request.QueryString["searchField"].IsEmpty() ) {
    selectCommand = "SELECT * FROM exportClient WHERE clientAccount = @0";
    searchTerm = Request.QueryString["searchField"];
    }

    if(IsPost){
     var selectedData = db.Query(selectCommand, searchTerm);
    }

And Then:

<body>
  <div class="col_12">
    <form method="get">
        <label>search</label><input type="text" class="col_3" name="searchField" />
        <button type="submit" class="button red" value="search">search</button>
    </form>
</div>


    @if(!Request.QueryString["searchField"].IsEmpty() ){
            foreach(var row in db.Query(selectCommand, searchTerm)) {
              <div class="col_12 box">
                 <form method="post">
                       // HERE IS THE FORM POPULATED
                  </form>
              </div>
             }
    } else { 
              <div class="col_12 box">
                 <form method="post">
                       // HERE IS THE FORM NOT POPULATED
                  </form>
              </div>
      }
</body>

But what is happening is that the form that is not populated is always showing up when i enter the page, and i need that the only thing that user see when enter the page is the input field to do the search.

What am i doing wrong ?


Solution

  • I'm not sure of having understood your goal, but in my opinion your main problem is to detect if either exists or not a query string.

    I think that your code should be like this

    @if(Request.QueryString.HasKeys())
    {
      if(!Request.QueryString["searchField"].IsEmpty() ){
        <p>searchField has value</p>
      } else {
        <p>searchField hasn't value</p>
      }
    }