Web Development 101: Part 6, Creating an Add Data page

To this point you've seen how to create a web site in WebMatrix, and how to use styling and layout to make your pages smaller and easier to maintain, as well as quicker for the browser to download and render. You created these pages to be dynamic and data-driven, and in this article you'll see how you can create a page that will add data to your database.

Creating and Linking an Add Page

Using WebMatrix, in the Files Workspace, create a new page and call it 'AddMovie.cshtml'.

Remove the default content for the page that was created for you by WebMatrix, and replace it with

<h1>Add a New Movie to the database</h1>

Now go back to your 'datamovies.cshtml' page. Open it, and it should look something like this:

@{
    var db= Database.Open("Movies");
    var sqlQ = "SELECT * FROM Favorites";
    var data = db.Query(sqlQ);   
}
 
<div id="movieslist">
  <ol>
    @foreach(var row in data){
      <li><a href="#">@row.Name, @row.Genre, @row.ReleaseYear</a></li>
    }
  </ol>
</div>
 

Before the closing </div>, add the following line of HTML. If you remember from an earlier article, this is an anchor, which is how HTML defines a link to another page.

<a href="AddMovie.cshtml">Add a new movie</a>

Run the site and view the page in the browser. It should look something like this:

alt

Click the 'Add a new movie' link, and you'll be taken to the page that you created earlier.

clip_image005

There isn't a lot in it right now. You'll add that in the next step.

As an added exercise, you may have noticed that the 'Add a New Movie to the Database' text is styled differently from the rest. It's a <h1>, but it hasn't been styled the same way as the header h1. See if you can fix that. (Hint, the header h1 is considered a child of the <header> tag, but this isn't. What would you add to the CSS file to style this the same way?)

Creating an Add Movie Form

Typically, when using HTTP your browser makes requests to the server using the GET verb from the HTTP protocol, which, as its name suggests, gets information from the server. You’ve been doing this all along, but may not have realized it, because using GET is implicit in the way browsers request pages. The HTTP protocol also supports a variable called POST which allows you to send information back to the server.

It’s nice to have an application that is dynamic, as you’ve seen, but the logical next step would be to ask how difficult it would be to send data to the server, have the server do something with the data, and then return the result. I’m sure you’ve seen hundreds of sites where you type in some information and press a Submit button to send that information to the server.

Such applications use an HTML form. When you click Submit, the browser sends the information in the form fields to the server using the POST verb. Again, all this happens under the hood, you don’t need to do anything special to use it, but it’s useful for your code on the server side to know what kind of verb a request is using, so the server can respond accordingly. You’ll see how to do that to add movies to your database.

We'll start with a very simple form. It's not very pretty, but it gets the job done.

     <h1>Add a New Movie to the Database</h1>
       <form action="" method="post">
         <p>Name:<input type="text" name="formName" /></p>
         <p>Genre:<input type="text" name="formGenre" /></p>
         <p>Year:<input type="text" name="formYear" /></p>
         <p><input type="submit" value="Add Movie" /></p>
     </form>

Here's how it will look. Like I said, not very pretty.

clip_image006

If you couldn't figure out the added exercise from earlier, you can easily fix your CSS so that your new <h1> tag has the same CSS style as our header <h1> tag. Open your movie.css file that we created in part 3 - Getting Some Style and add to your file:

h1 { font-size: xx-large;font-weight: normal;padding: 0px;margin: 0px; }

Now try running your "AddMovie.cshtml" page again. Both <h1> tags should have the same style applied to them.

clip_image006

Now let's take a look at the HTML we've just written to create this form.

<form action="" method="post">

The first new thing is the <form> tag. This defines the form, and tells the server that when the user presses the <submit> button, which must be present in the form, that the action will be an HTTP POST. By virtue of the fact that the action parameter is empty, this same page (i.e. AddMovie.cshtml) will process the post from the form.

<p>Name:<input type="text" name="formName" /></p>
<p>Genre:<input type="text" name="formGenre" /></p>
<p>Year:<input type="text" name="formYear" /></p>
 

Within the <form> tag you’ll see that there are three <input> controls. These use the HTML <input> control, which can have a number of type settings, and in this case the type is 'text', which gives you a basic text box that the user can input text with. Each is given a name which will be the variable that the server uses to store the value that the user enters into the text box before submitting.

<p><input type="submit" value="Add Movie" /></p>

Finally we have an <input> control with type 'submit' which defines the submit button. When the user presses this button, the HTTP POST action will be invoked and the data that the user entered will be sent to the server.

Right now if you press the button, nothing will happen. This is because you haven't written the code to handle the postback from the server yet. You'll do that next.

Handling the data from the Form

When you created the form, you left the action parameter empty, which means that you are specifying that this page should accept the form submission.

You can do that by updating your 'AddMovie.cshtml' page with some code to execute whenever the page loads. To do this, add a code block at the top of the page, like this:

     @{
       // Code to execute
     }
      
     <h1>Add a New Movie to the Database</h1>
     <form action="" method="post">
       <p>Name:<input type="text" name="formName" /></p>
       <p>Genre:<input type="text" name="formGenre" /></p>
       <p>Year:<input type="text" name="formYear" /></p>
       <p><input type="submit" value="Add Movie" /></p>
     </form>   

Earlier you saw that the first time you call the page, by typing its address in your browser (or clicking Run to launch the file), your browser requests the pages using the HTTP GET verb to get the page. Later, when you pressed the Submit button, because the action property was blank, the HTTP POST operation just called the same page.

So, in your code, you'll need to know a way to figure out is the page being retrieved using a GET or is it being executed using a POST. Fortunately, the .NET Framework lets you check the verb without getting into the complexity of breaking up the HTTP headers to inspect what type of message you’re getting; you simply use the If(IsPost) check, which, when true, means the user has used a form to post the information.

     @{
       If(IsPost)
       {
         // Do something on the POST
       }
     }   

When you set up the form, you gave names (formName, formGenre, formYear) to the values that the user submits. When the browser calls the server, it will use this by sending a message that contains 'formName=something', 'formGenre=something','formYear=something' and so on.

So, you'll first need to set up some server variables to hold these, and then you'll read them off the HTTP post. This is a lot easier than it sounds :)

     @{
       var MovieName="";
       var MovieGenre="";
       var MovieYear="";
       if(IsPost){
         MovieName=Request["formName"];
         MovieGenre=Request["formGenre"];
         MovieYear=Request["formYear"];
       }
     }

Here you can see that 3 variables have been set up (MovieName, MovieGenre and MovieYear) and these are initialized with the values that the user submitted. In the next step you'll add the code to open the database and add this information to it.

Adding to the Database

In the previous article, when you retrieved data from the database, you write a SQL 'SELECT' query which selected the data from the database for you to read. In this case you are adding data to the database, which uses an insert query.

The SQL INSERT command uses the following syntax

INSERT INTO Table (Column1, Column2, ...ColumnN) VALUES (Value1, Value2, ... ValueN)

Let's see how do to that in our code:

     @{
     var MovieName="";
     var MovieGenre="";
     var MovieYear="";
       if(IsPost){
         MovieName=Request["formName"];
         MovieGenre=Request["formGenre"];
         MovieYear=Request["formYear"];
         var SQLINSERT = "INSERT INTO Favorites (Name, Genre, ReleaseYear) VALUES (@0, @1, @2)";
         var db = Database.Open("Movies");
         db.Execute(SQLINSERT, MovieName, MovieGenre, MovieYear);
       }
     }

You can see that we create a string called SQLINSERT to hold the command. Razor allows you to specify parameterized values in this string, so instead of trying to add the values for 'MovieName', 'MovieGenre' and 'MovieYear', to the string, we can simply use @0, @1 and @2. When we execute the query, the framework allows us to substitute them in. You can also 'clean' the parameters before entering them into the query. This prevents people passing SQL code as a parameter, in an attack called a 'SQL Injection Attack'.

Next we open the database, and then we call the Execute method on the database to tell it to run this insert query. The values get substituted in, and the values get added to the database.

Let's add one more line after the db.Execute(), which will redirect the user back to the page where they can view the favorite movies, and they can see the results of what they just added.

Response.Redirect("datamovies.cshtml");

Now run the page, and you'll see the form. Add some data to it:

clip_image007

Press the 'Add Movie' button, and the server will add the data to the database, and then redirect you back to the list to see the results, and you can see that your new favorite movie has been added!

clip_image009

Important: In this article you saw how to take user input and add it directly to the database. While learning the basics, this is ok, but before you deploy a production site, you'll have to remember to do the following

- Check the input parameters for valid data, and give the user accurate feedback on what they've entered incorrectly. For example, if they don't enter a good value for 'Year', they should be informed of this, instead of allowing anything to go to the database

- Check the input parameters for values that might be used by a nefarious hacker to damage your database. A common attack is called SQL Injection where the user sends a SQL command in a form, and the code on the server executes this, potentially damaging or exposing private data.

You can learn more detail about using databases in WebMatrix here: http://www.asp.net/webmatrix/tutorials/5-working-with-data

Summary

You've now seen how to add data to your database of movies. You created an HTML form to handle the users input and saw how to add the values directly to the database. You then saw how to redirect the user, automatically, once the data was added, back to the list page in order to see the data that they had added.

In the next article you'll take that a step further and add functionality that allows the user to edit the data that they already have.

Continue to Part 7, where you’ll learn how to create an ‘Edit Data’ page.

You can discuss this article using the adjacent Facebook talkback.

For technical questions please visit our discussion forums, where we have a vibrant community of developers like you, as well as Microsoft engineers who are ready to answer your questions!