ASP.NET Forums Website Part 5 Adding the NewPost Page
Adding the NewPost.aspx PageThe next thing we need to do is add in the NewPost.aspx page so that we can make new posts from the web site. To make a post a user must be logged in, so before we add in the NewPost page we need to enable the creation of users and make an account we can login to for testing. To do this:
- Click the ASP.NET Configuration icon in your Solution Explorer.
- In the ASP.NET Web Site Administration Tool click the Security tab.
- Under the Users header click Select authentication type.
- Select From the internet.
- Click Done.
- Under the Users header click Create user.
- Fill out the Create User form and click Create User.
- Close the ASP.NET Web Site Administration Tool.
We chose Server Intellect for its dedicated servers, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar.
The NewPost page will need to contain two textboxes for the user to input a Title and a Message. Furthermore, it will need to contain a button to submit the post and also have a condition in which it displays the new post form to a user who is logged in and a Login Control to a user who is not logged in. To do this, we will be adding in a LoginView Control and placing our form stuff in the LoggedInTemplate and a Login Control into the AnonymousTemplate. To begin:
- Right click the project in your Solution Explorer.
- Select Add New Item…
- Select a Web Form and name it NewPost.aspx.
- Ensure that the Select master page checkbox is checked and click Add.
- Select the MasterPage.master we added earlier and click OK.
- Open the NewPost.aspx page in Design mode.
- Expand the Login tab in your Toolbox.
- Drag and drop a LoginView Control into the ContentPlaceHolder1 on the Web Form.
The LoginView Control contains two templates, Anonymous and LoggedIn. First, we will add content to the AnonymousTemplate. To do this:
- Expand the LoginView Tasks menu.
- Select AnonymousTemplate in the Views DropDownList.
- Drag and drop a Login Control into the editable area of the LoginView Control.
Next, we need to add content to the LoggedIn view. To do this:
- Expand the LoginView Tasks menu.
- Select LoggedInTemplate in the Views DropDownList.
- Select the editable area of the LoginView Control.
- From the top menu, select Table -> Insert Table.
- Insert a table that has 3 rows and 2 columns and choose not to specify the width.
- In the top left cell type in Title:.
- In the cell under this, type in Message:.
- Drag and drop a TextBox Control into the top right cell, to the right of Title:.
- Change the ID property of the TextBox to txtTitle.
- Set the Columns property to 50.
- Set the MaxLength property to 255.
- Drag and drop a RequiredFieldValidator next to the txtTitle TextBox.
- Change the ID property to rfvTitle.
- Set the ErrorMessage property to Title is required.
- Set the Text property to *.
- Set the ControlToValidate property to txtTitle.
- Drag and drop a TextBox Control beneath this cell, to the right of Message:.
- Change the ID property of the TextBox to txtMessage.
- Set the TextMode property to MultiLine.
- Set the Rows property to 6.
- Set the Columns property to 40.
- Drag and drop a RequiredFieldValidator next to the txtMessage TextBox.
- Change the ID property to rfvMessage.
- Set the ErrorMessage property to Message is required.
- Set the Text property to *.
- Set the ControlToValidate property to txtMessage.
- Select the two cells in the bottom row and merge them.
- Set the alignment of the bottom row to center.
- Drag and drop a Button Control into the bottom row.
- Change the ID property of the Button to btnSubmit.
- Set the Text property of the Button to Submit.
- Drag and drop a ValidationSummary Control underneath the btnSubmit Button.
Now you should have a simple form for adding a new post that looks similar to this:
If you load the website up now and navigate to the NewPost page, then login using the account we created earlier, you should see your form. Leaving everything blank hit the Submit button to verify that your validation is working. We want to make sure that the validation is correct here before we add the code to actually create posts in our database because we don’t want to have any invalid posts in the database.
If you’re looking for a really good web host, try Server Intellect – we found the setup procedure and control panel, very easy to adapt to and their IT team is awesome!
Next, we are going to add the code to store the post in the database on the event that the Submit button is clicked. To do this, double click the Submit button to generate the click event method. Then in the btnSubmit Click event method we need to add the following code:
Code Block
NewPost.aspx.cs
The btnSubmit_Click event method
SqlDataReader rdr = null;
//setup our data to insert into the post table
string postUserName = Page.User.Identity.Name;
string postTitle = ((TextBox)LoginView1.FindControl("txtTitle")).Text;
string postMessage = ((TextBox)LoginView1.FindControl("txtMessage")).Text;
DateTime postDateTime = DateTime.Now;
int topicId = int.Parse(Request.QueryString["id"]);
//Add appropriate data to the post table
//setup our connection to the db
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ForumDBConnectionString"].ConnectionString);
//create our sql command object
SqlCommand cmd = new SqlCommand("Insert INTO Posts(TopicId, PostTitle, PostUserName, PostDateTime) VALUES (@TopicId, @PostTitle, @PostUserName, @PostDateTime)", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@TopicId", topicId);
cmd.Parameters.AddWithValue("@PostTitle", postTitle);
cmd.Parameters.AddWithValue("@PostUserName", postUserName);
cmd.Parameters.AddWithValue("@PostDateTime", postDateTime);
using (conn)
{
conn.Open();
cmd.ExecuteNonQuery();
}
//setup data to insert into the comment table
int postId = 0; //set this later when we get it back from the db
conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ForumDBConnectionString"].ConnectionString);
cmd = new SqlCommand("Select * FROM Posts WHERE TopicId=@TopicId AND PostTitle=@PostTitle AND PostUserName=@PostUserName AND PostDateTime=@PostDateTime", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@TopicId", topicId);
cmd.Parameters.AddWithValue("@PostTitle", postTitle);
cmd.Parameters.AddWithValue("@PostUserName", postUserName);
cmd.Parameters.AddWithValue("@PostDateTime", postDateTime.ToString());
using (conn)
{
conn.Open();
rdr = cmd.ExecuteReader();
if (rdr.Read())
{
postId = int.Parse(rdr["PostId"].ToString());
}
}
//Add appropriate data to the comments table
conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ForumDBConnectionString"].ConnectionString);
cmd = new SqlCommand("Insert INTO Comments(PostId, CommentUserName, CommentMessage, CommentDateTime) VALUES (@PostId, @CommentUserName, @CommentMessage, @CommentDateTime)", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@PostId", postId);
cmd.Parameters.AddWithValue("@CommentUserName", postUserName);
cmd.Parameters.AddWithValue("@CommentMessage", postMessage);
cmd.Parameters.AddWithValue("@CommentDateTime", postDateTime);
using (conn)
{
conn.Open();
cmd.ExecuteNonQuery();
}
//Add appropriate data to the topics table
conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ForumDBConnectionString"].ConnectionString);
cmd = new SqlCommand("Update Topics Set LastPostTitle=@LastPostTitle, LastPostUserName=@LastPostUserName, LastPostDateTime=@LastPostDateTime WHERE TopicId=@TopicId", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@LastPostTitle", postTitle);
cmd.Parameters.AddWithValue("@LastPostUserName", postUserName);
cmd.Parameters.AddWithValue("@LastPostDateTime", postDateTime);
cmd.Parameters.AddWithValue("@TopicId", topicId);
using (conn)
{
conn.Open();
cmd.ExecuteNonQuery();
}
Response.Redirect("Topic.aspx?id=" + topicId.ToString());
Let’s review what this code is actually doing. First, we setup the data we need to insert into the Posts table. We grab the TopicId, the PostTitle from the txtTitle TextBox, the PostUserName based on the user who is currently logged in, and the PostDateTime using DateTime.Now. Then, we add those into the Post table respectively via a SQL command
.
When we add a new entry to the Post table, a PostId is generated for it. Next, we want to figure out what PostId was generated for the Post we just added, so we select the Post from the table that we just inserted, and set that to a local variable postId.
.
When we add a new entry to the Post table, a PostId is generated for it. Next, we want to figure out what PostId was generated for the Post we just added, so we select the Post from the table that we just inserted, and set that to a local variable postId.
Then, we have all of the data needed to construct the first comment to the post, which is the message that the user entered into the txtMessage box. So, we insert a PostId, CommentUserName, CommentMessage from the txtMessage TextBox, and CommentDateTime into the Comments table respectively via a SQL command.
Next, we need to update the latest post data in the Topics table based on what topic this post was added to. To do this, we update the Topics table at our current TopicId and update the LastPostTitle, LastPostUserName, and LastPostDateTime in the Topics table respectively.
To test this out, go ahead and load up the website, navigate to the new post page, login, and add a new post. Then, check the posts for the topic you added to ensure that a post was made. Check that post to make sure your message is the first comment, and finally check the home page to make sure that the topic you posted in reflects the last post data.
Yes, it is possible to find a good web host. Sometimes it takes a while. After trying several, we went with Server Intellect and have been very happy. They are the most professional, customer service friendly and technically knowledgeable host we’ve found so far.
ASPdotNET Forums Website Tut
ASPdotNET Forums Website Tut
No comments:
Post a Comment