Working With Forms in ASP.Net Web Pages 2

Introduction

Today we'll learn to create a form using HTML elements and use them from the ASP.NET Web Pages 2 (Razor). Since you already know how to connect to the database from the page and Display Data in Web Page, So we'll learn here the basics of forms and apply searching in the database.

In  that context we need to create some HTML elements in the forms of web pages using the following sections:

  • Working with Forms
  • Reading Values
  • Working with SQL Queries
  • Apply Query to Web Page

Working with Forms

We'll create some HTML elements in the forms using the following procedure.

Step 1: Insert the following highlighted code:

<h1>Best Cricketers</h1>

<form method="get">

    <div>

        <label for="searchCricketer">Find Cricketer:</label>            

        <input type="text" name="searchCricketer" value="" />

        <input type="Submit" value="Search Cricketer" />

    </div>

</form>

In the code above we create a form in which there are two elements that exist named TextBox and button. We've put both elements inside the form element otherwise nothing will be submitted. We are using "Get" here because we're creating a form that does not make any changes on the server.

Step 2: Run the current Cricketers.cshtml page. The page will look such as below:

Searching in WebMatrix

Step 3: Enter the cricketer name to search in the TextBox. However the search is not complete because we've not defined the blocks but the URL of the page contain the query string as you can see in the following URL code:

http://localhost:31257/Cricketers.cshtml?searchCricketer=Sachin+Tendulkar

Reading Values

We've already created some code that accesses the values from the database. Now we use code to access the value of the TextBox and return the value. As we've used the Query String here, so we need to use the following code in the code:

var search = Request.QueryString["searchCricketer"];

The Request.QueryString includes the values of elements that were submitted as part of the GET operation. It contains a collection of the value. If we need to get any individual value then we need to specify it. Therefore we need to have a "name" attribute of the "input" element in which we defined the query string.

Working with SQL Queries

  • If we want to display the entire table then we need to use the following query:

    Select * from Cricketers
     

  • If we want to display any specific then we need to use the following query:

    Select * from Cricketers where name= 'Sachin Tendulkar'
     

  • If we want to display any user specified record then we need to pass the parameter as shown below:

    Select * from Cricketers where name= @0

Apply Query to Web Page

Now we apply the query to the web page and update our code. Use the following procedure to do that.

Step 1: Replace the code block with the code below:

@{

   var CricDb= Database.Open("Cricketer Site");

   var CommandText = "Select * from Cricketers";

   var search = "";

   

   if(!Request.QueryString["searchCricketer"].IsEmpty()){

       CommandText = "Select * from Cricketers where Name= @0";

       search = Request.QueryString["searchCricketer"];

   }

 

   var CricData = CricDb.Query(CommandText, search);

   var CricGrid= new WebGrid(source: CricData, rowsPerPage:4);

}

With the use of the code above, the page execution (every time) opens the database and with CommandText gets all the records from the table in the database. If the user wants to search the record, then the code sets a CommandText to a different query. With the regard of CommandText the code calls the CirdDb.Query to run the query and search the record. If the search is empty then there is no parameter passed. Finally the code initializes the webgrid helper by using the query results.

Step 2: Run the page and enter the value to search and click on the button.

Search record

Note: Note that the TextBox is emptied when the search process is complete, in ohter words it didn't remember what you entered.

Search record empty

To update this, we need to update the value attribute as shown below:

Remember the Record to search

Search for Any Word in the Name

You can see that if we do not enter the full name in the TextBox then there is nothing record to show like.

Step 1: If we enter a short name to search for:

Search with anyword

Then we need to update our code.

Step 2: Modify the code with the highlighted code below:

if(!Request.QueryString["searchCricketer"].IsEmpty()){

     CommandText = "Select * from Cricketers where Name LIKE @0";

     search = "%" + Request["searchCricketer"] + "%";

}

This code uses the same logic that is applied earlier, except that the CommandText uses the "LIKE" operator and the code puts "%" before and after the search.

Step 3: Now enter the record to search such as shown below:

Search with any word

Complete Code:

@{

   var CricDb= Database.Open("Cricketer Site");

   var CommandText = "Select * from Cricketers";

   var search = "";

   

   if(!Request.QueryString["searchCricketer"].IsEmpty()){

       CommandText = "Select * from Cricketers where Name LIKE @0";

       search = "%" + Request["searchCricketer"] + "%";

   }

 

   var CricData = CricDb.Query(CommandText, search);

   var CricGrid= new WebGrid(source: CricData, rowsPerPage:4);

}

 

<!DOCTYPE html>

 

<html lang="en">

    <head>

        <meta charset="utf-8" />

        <title>Best Cricketers</title>

        <style type="text/css">

            .CricGrid { margin3pxborder-collapsecollapsewidth450px}

            .CricGrid th.CricGrid td { border1px solid #C0C0C0padding5px}

            .head { background-color:#0fffont-weightboldcolor#FFF}

            .alt { background-color#0ffcolor#000} 

        </style>

    </head>

    <body>

        <h1>Best Cricketers</h1>

        <form method="get">

            <div>

                <label for="searchCricketer">Find Cricketer:</label>            

                <input type="text" name="searchCricketer" value="@Request.QueryString["searchCricketer"]" />

                <input type="Submit" value="Search Cricketer" />

            </div>

        </form>

        <div>

            @CricGrid.GetHtml(

                tableStyle: "CricGrid",

                headerStyle: "head",

                alternatingRowStyle: "alt",

                columns: CricGrid.Columns(

                    CricGrid.Column("Name"),

                    CricGrid.Column("Team"),

                    CricGrid.Column("Grade")

                )

            )

        </div>

    </body>

</html>

Summary

You have learned here how to create an input form and handle the user requests for searching the record using a form in ASP.NET Web Pages 2. In the next article we'll perform the addition of Cricketers to the database. Thanks for reading.

Up Next
    Ebook Download
    View all
    Learn
    View all