Question

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 ?

Was it helpful?

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

OTHER TIPS

There are a number of potential issues I can see with your code, hopefully you can put these together to achieve what you wanted:

  1. As Selva points out, you are missing the action attribute on your forms.
  2. The selectedData variable you create inside your IsPost() block goes out of scope before you do anything with it. Perhaps you didn't include all your code though, so ignore this if it just isn't relevant to the question.
  3. To answer the main question: if you don't want the empty form to appear when the user hasn't yet performed a search, surely you just need to completely remove the else block - including the empty form - from your HTML?

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top