Question

need this in #c . You will now add server side validation code to the frmPersonnel...

need this in #c

. You will now add server side validation code to the frmPersonnel page. Currently, when the Submit button is pressed, the frmPersonnelVerified page is displayed. This is because the frmPersonnelVerified page is set as the Submit button's PostBackUrl property. Instead of having the page go directly to the frmPersonnelVerified page when the Submit button is pressed, we want to do some server side validation. If any of the validation rules fail, we will redisplay the frmPersonnel page with the fields in question highlighted in yellow with an error message displayed.

First, it is important to understand what is currently happening when the submit button is pressed. This is causing a postback of the form to the frmPersonnelVerified form. When this postback happens, all of the data in the fields on the frmPersonnel form are sent to the frmPersonnelVerified form as name value pairs. In the Page_Load code of frmPersonnelVerified these values are picked up from the Request object and displayed. Each name value pair will be in the Request object as the ID of the control containing the value and the value itself. We can pass data between pages by using Session state instead. In order to do validation on the values but still have the values visible on the frmPersonnelVerified page, we will need to change not only the PostBack URL of the frmPersonnel page but also how the frmPersonnelVerified form is getting the data—it will need to get it from Session state rather than from the Request object.

In order to do this, we will make the following changes.

Clear the Submit button PostBackURL Property on the frmPersonnel form. Remove the value in the PostBackUrl that is highlighted.

In the btnSubmit_Click event handler get each value from the data entry fields and set Session state items for each. (instructions below)

Change the frmPersonnelVerified code behind to get the values from the Session state items you created in the previous step. (instructions below)

When you are done with these steps, you should be able to enter data on the frmPersonnel data entry form and then click the Submit button. The frmPersonnelVerified page should then be displayed with the values that were in the data entry fields on frmPersonnel.

23. Add a label to the frmPersonnel form with an ID of lblError. Do not place the label to the right or left of any of the controls on the form. Add it below the controls or above the controls. The text property of this label should be set to an empty string.

24. Add code to perform server side validation in response to the submit button being clicked. Here are the business rules we want to enforce (remember this will be server C# code in the frmPersonnel code behind): Fields may not be empty or filled with spaces. If any field is empty, turn that field background color to yellow and add to/create an error message to be shown in the error label. The end date must be greater than the start date. If the end date is less than the start date, turn both date fields yellow and add to/create an error message to be shown in the error label. If all fields validate properly then the session state items should be set properly and the user should see the frmPersonnelVerified form with all the values displayed.

frmPersonnel.aspx Lab Hints

1. The server side validation should be in the Submit button's event handler. There is a Trim method on the string object that will automatically remove spaces from the beginning and end of a string. To test if txtFirstName is empty or filled with spaces, use the following code.

 if (Request["txtFirstName"].ToString().Trim() == "")

2. To set the background color of the txtFirstName field, use the following code.

txtFirstName.BackColor = System.Drawing.Color.Yellow;

3. To set a value in session state and redirect the response to the frmPersonnelVerified.aspx do the following. txtFirstName is the key and txtFirstName.Text is the value.

Session["txtFirstName"] = txtFirstName.Text;
//Need to set session variables for all text boxes
Response.Redirect("frmPersonnelVerified.aspx");

4. You may want to create variables to work with for validation rather than using the Request item objects directly.

To turn a string into a DateTime object you can use the DateTime method Parse. If you had a date value stored in a string called strDate, you could turn it into a DateTime object like this.

DateTime myDateTimeObject = DateTime.Parse(strDate);

You can compare two DateTime objects by using the DateTime.Compare method. If you had two DateTime objects called dt1 and dt2 you can check to see if dt1 is greater than dt2 by doing this.

if (DateTime.Compare(dt1,dt2) > 0)

DateTime.Compare will return a 0 if the two dates are equal, a 1 if dt1 is greater than dt2, and a -1 if dt1 is less than dt2.

If you put in an invalid date for either of the date fields, you will get an exception/server error when trying to parse the values. We will address this in a later lab—for now make sure you enter valid dates (valid meaning a date in the form of mm/dd/yyyy).

5. An example of the code you might want to use to test if the end date is after the start date follows.

DateTime startDate = DateTime.Parse(Request["txtStartDate"]);
DateTime endDate = DateTime.Parse(Request["txtEndDate"]);
if (DateTime.Compare(startDate, endDate) > 0)
{
txtStartDate.BackColor = System.Drawing.Color.Yellow;
txtEndDate.BackColor = System.Drawing.Color.Yellow;
Msg = Msg + "The end date must be a later date than the start date."; 
//The Msg text will be displayed in lblError.Text after all the error messages are concatenated
validatedState= false; 
//Boolean value - test each textbox to see if the data entered is valid, if not set validState=false. 
//If after testing each validation rule, the validatedState value is true, then submit to frmPersonnelVerified.aspx, if not, then display error message
}
else
{
txtStartDate.BackColor = System.Drawing.Color.White;
txtEndDate.BackColor = System.Drawing.Color.White;
}

Remember to clear the PostBackURL property of the Submit button!

frmPersonnelVerified.aspx Lab Hints

When using the Session state in frmPersonnel.aspx for txtFirstName, you used the following code: Session["txtFirstName"] = txtFirstName.Text;

To get this same value back from the session we use the key and the Session object in the Page_Load of frmPersonnellVerified.aspx (instead of using Request, use Session) as follows.

Session["txtLastName"].ToString()
0 0
Add a comment Improve this question Transcribed image text
Answer #1

A web form application is created based on the requirement given in the question. In the application i have added frmPersonnel.aspx and frmPersonnelVerified.aspx pages and implemented the code as described in requirement

Below are the screens to show the application i created and the two pages

Open Visual Studio and create a new project

な New Project Recent .NET Framework 4.5 Sort by: Default Search Installed Templates (Ctrl+D ρ . 4 Installed Windows Forms App

Once the project solution created some default pages will be created as shown below

Default.aspx嗌ㄨ Solution Explorer <XA Page Title-Home Page Language-са MasterPage File--/site . Master AutoEventwireup-t

In this i have added two files frmPersonnel.aspx and frmPersonnelVerified.aspx by right click on the project and add new pages

In a new window give name as frmPersonnel.aspx

Again right click and add another file with name frmPersonnelVerified.aspx

Add New Item PersonelValidation Installed Sort by: Default Search Installed Templates (Ctrl+D ρ . Visual C# Type: Visual C# A

Once you added two files, in solution explorer the files will be listed as shown in below screen

In the frmPersonnel.aspx copy the below code to add the label and textbox controls in the file hightlighed in screen

******************************frmPersonnel.aspx*****************************

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="frmPersonnel.aspx.cs" Inherits="PersonelValidation.frmPersonnel" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td><asp:Label ID="lblFirstName" runat="server" Text="First Name:"></asp:Label></td>
<td><asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="lblLastName" runat="server" Text="Last Name:"></asp:Label></td>
<td><asp:TextBox ID="txtLastName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="lblSurName" runat="server" Text="Sur Name:"></asp:Label></td>
<td><asp:TextBox ID="txtSurName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="lblStartDate" runat="server" Text="Start Date:"></asp:Label></td>
<td><asp:TextBox ID="txtStartDate" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="lblEndDate" runat="server" Text="End Date:"></asp:Label></td>
<td><asp:TextBox ID="txtEndDate" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" /></td>
<td><asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" /></td>
</tr>
</table>
<asp:Label ID="lblError" runat="server" Text=""></asp:Label>
  
  
</div>
</form>
</body>
</html>

************************************END******************************************

Now again open the same file code behind file which is highlighted in below screen and copy the below given code, all the code are explained in the inline comments

****************************frmPersonnel.aspx.cs***************************

using System;

namespace PersonelValidation
{
public partial class frmPersonnel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblError.ForeColor = System.Drawing.Color.Red;
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
//Local variables to store the text values
string firstName = txtFirstName.Text;
string lastName = txtLastName.Text;
string surName = txtSurName.Text;
string strStartDate = txtStartDate.Text;
string strEndDate = txtEndDate.Text;
//start and end date variables with DateTime keyword
DateTime startDate = new DateTime();
DateTime endDate = new DateTime();
//Boolean variable to check the form is valid or not
bool validatedState = true;
//The Msg text will be displayed in lblError.Text after all the error messages are concatenated
string errorMessage = string.Empty;

//If first name is empty string, record error message
if (string.IsNullOrWhiteSpace(firstName.Trim()))
{
txtFirstName.BackColor = System.Drawing.Color.Yellow;
errorMessage = "First Name is empty!<br/>";
validatedState = false;
}
//If last name is empty string, record error message
if (string.IsNullOrWhiteSpace(lastName.Trim()))
{
txtLastName.BackColor = System.Drawing.Color.Yellow;
errorMessage += "Last Name is empty!<br/>";
validatedState = false;
}
//If sur name is empty string, record error message
if (string.IsNullOrWhiteSpace(surName.Trim()))
{
txtSurName.BackColor = System.Drawing.Color.Yellow;
errorMessage += "Sur Name is empty!<br/>";
validatedState = false;
}
//If start date is empty string, record error message
if (string.IsNullOrWhiteSpace(strStartDate.Trim()) || !DateTime.TryParse(strStartDate, out startDate))
{
txtStartDate.BackColor = System.Drawing.Color.Yellow;
errorMessage += "Start Date is not valid!<br/>";
validatedState = false;
}
//If end date is empty string, record error message
if (string.IsNullOrWhiteSpace(strEndDate.Trim()) || !DateTime.TryParse(strEndDate, out endDate))
{
txtEndDate.BackColor = System.Drawing.Color.Yellow;
errorMessage += "End Date is not valid!<br/>";
validatedState = false;
}
//If end date is lesser than start date, record error message
if (validatedState && DateTime.Compare(startDate, endDate) > 0)
{
txtStartDate.BackColor = System.Drawing.Color.Yellow;
txtEndDate.BackColor = System.Drawing.Color.Yellow;
errorMessage += "The End Date must be a later date than the Start Date.";
//The Msg text will be displayed in lblError.Text after all the error messages are concatenated
validatedState = false;
//Boolean value - test each textbox to see if the data entered is valid, if not set validState=false.
}

//If after testing each validation rule, the validatedState value is true,
//then submit to frmPersonnelVerified.aspx, if not, then display error message
if (validatedState)
{
Session["firstName"] = firstName;
Session["lastName"] = lastName;
Session["surName"] = surName;
Session["strStartDate"] = strStartDate;
Session["strEndDate"] = strEndDate;

Response.Redirect("frmPersonnelVerified.aspx");
}
else
lblError.Text = errorMessage;
}

//Cancel button click event
protected void btnCancel_Click(object sender, EventArgs e)
{
txtFirstName.Text = string.Empty;
txtLastName.Text = string.Empty;
txtSurName.Text = string.Empty;
txtStartDate.Text = string.Empty;
txtEndDate.Text = string.Empty;
}
}
}

**********************************END******************************************

Similarly follow the same previous steps to copy the code in the other file frmPersonnelVerified.aspx

PersonnelVerified.aspx.cs frmPersonnelVerified.aspx X frmPersonnel.as Default aspx <<Solution Explorer ead runat-server> ti

***************************************frmPersonnelVerified.aspx.aspx*************************************

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="frmPersonnelVerified.aspx.cs" Inherits="PersonelValidation.frmPersonnelVerified" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td><asp:Label ID="lblFirstName" runat="server" Text="First Name:"></asp:Label></td>
<td><asp:Label ID="lblFName" runat="server" Text="-"></asp:Label></td>
</tr>
<tr>
<td><asp:Label ID="lblLastName" runat="server" Text="Last Name:"></asp:Label></td>
<td><asp:Label ID="lblLName" runat="server" Text="-"></asp:Label></td>
</tr>
<tr>
<td><asp:Label ID="lblSurName" runat="server" Text="Sur Name:"></asp:Label></td>
<td><asp:Label ID="lblSName" runat="server" Text="-"></asp:Label></td>
</tr>
<tr>
<td><asp:Label ID="lblStartDate" runat="server" Text="Start Date:"></asp:Label></td>
<td><asp:Label ID="lblSDate" runat="server" Text="-"></asp:Label></td>
</tr>
<tr>
<td><asp:Label ID="lblEndDate" runat="server" Text="End Date:"></asp:Label></td>
<td><asp:Label ID="lblEDate" runat="server" Text="-"></asp:Label></td>
</tr>
</table>
</div>
</form>
</body>
</html>

*************************************************END***********************************************************

Now again open the same file code behind file which is highlighted in below screen and copy the below given code, all the code are explained in the inline comments

************************************************frmPersonnelVerified.aspx.cs***************************************

using System;

namespace PersonelValidation
{
public partial class frmPersonnelVerified : System.Web.UI.Page
{
//Page load event
protected void Page_Load(object sender, EventArgs e)
{
//Get the values from session and show them in the label controls
lblFName.Text = Convert.ToString(Session["firstName"]);
lblLName.Text = Convert.ToString(Session["lastName"]);
lblSName.Text = Convert.ToString(Session["surName"]);
lblSDate.Text = Convert.ToString(Session["strStartDate"]);
lblEDate.Text = Convert.ToString(Session["strEndDate"]);
}
}
}

*****************************************************END**************************************************************

Now run the pages in the browser

Output Screens

Validation Screens

And final redirect page screen

Add a comment
Know the answer?
Add Answer to:
need this in #c . You will now add server side validation code to the frmPersonnel...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • True/False 1. Browser-based validation can replace the need to write custom JavaScript code to validate user...

    True/False 1. Browser-based validation can replace the need to write custom JavaScript code to validate user input. 2. When you add a new property to an object that has been instantiated from a constructor function, the new property is available to all objects instantiated from the same constructor function. 3. Because objects in the browser object model are actually part of the web browser, you do not need to instantiate them in order to use them in your programs. 4....

  • NEED HELP with HTML with Javascript embedding for form validation project below. I have my code...

    NEED HELP with HTML with Javascript embedding for form validation project below. I have my code below but I'm stuck with validation. If anyone can fix it, I'd really appreciate. ****************************************************************************** CODE: <!DOCTYPE html> <!-- To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools | Templates and open the template in the editor. --> <html> <head> <title>Nice</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script> var textFromTextArea; function getWords(){ var text =...

  • Here is the description of the client and server programs that you need to develop in C using TCP: Suppose we have a simple student query system, where the server keeps student's info in an array...

    Here is the description of the client and server programs that you need to develop in C using TCP: Suppose we have a simple student query system, where the server keeps student's info in an array of struct student_info ( char abc123171 char name [101 double GPA; To simplify the tasks, the server should create a static array of 10 students with random abc123, name, and GPA in the server program. Then the server waits for clients. When a client...

  • create a handler you can visit to set up your database table. It contains all the...

    create a handler you can visit to set up your database table. It contains all the fields needed to make a simple workout tracker. name - the name of the exercise reps - the number of times the exercise was performed weight - the weight of the weights used date - the date the exercise was performed lbs - a boolean indicating if the measurement is in lbs or kg. 1 indicates lbs, 0 indicates kgs. Requirements You need to...

  • Form Processing HTML One of the most ubiquitous uses of JavaScript is validating form data on...

    Form Processing HTML One of the most ubiquitous uses of JavaScript is validating form data on the client side before it is submitted to the server. It is done everywhere because it is fast and it gives you a great deal of flexibility in how you handle errors insofar as the GUI is concerned. Attached is an image of some code I wrote (so Blackboard can't mess it up). Some things to notice that will help you with the lab....

  • Develop an HTML form that could be used to enter your book information (Books, Authors, and...

    Develop an HTML form that could be used to enter your book information (Books, Authors, and Publishers) start with the HTML/JavaScript template provided Expand upon it! What field information would you enter into a system? Have your form use more then just character text fields ... radio buttons, pick lists, and other elements make your form easier to use and you don't need to do lots of JavaScript checks. What fields would be mandatory ... which could be left blank?...

  • In this exercise, you’ll add code to a form that converts the value the user enters...

    In this exercise, you’ll add code to a form that converts the value the user enters based on the selected conversion type. The application should handle the following conversions: 1. Open the Conversions project. Display the code for the form, and notice the rectangular array whose rows contain the value to be displayed in the combo box, the text for the labels that identify the two text boxes, and the multiplier for the conversion as shown above. Note: An array...

  • I need to write a function in C# that would validated user entry for Payment Code...

    I need to write a function in C# that would validated user entry for Payment Code in the form. The form is used to collect information about payments. User can enter ad many rows/entries as he/she wishes by clicking "Add another Payment" button on the buttom. There is a Payment Code field that needs to be validates. It's a drop down list, with many values but the user is eligible to select only two of them: Meal and Travel. Every...

  • Looking for some help here: Edit GetPhoneData to add more input validation by setting ranges for...

    Looking for some help here: Edit GetPhoneData to add more input validation by setting ranges for values Brands (Samsung, iPhone, Google) Models (Galaxy, Note, 8, X, Pixel) Price ($0.01-$2000) Include a comment about your addition, you can be creative, add components (or not), individualize this. Extra Credit (Samsung must be paired to Galaxy or Note) 2 points Below is the code: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Cell_Phone_Test {...

  • Here is my skeleton code to this C# assignement I need to add a few things,...

    Here is my skeleton code to this C# assignement I need to add a few things, Change the the switch to If and Else-If statements (and test it is still working here) Add a third "Submit" button called SubmitButton In your If and Else-If add a condition if city is Honolulu and SubmitButton is checked. Display "Honolulu is the best place to be this time of year! I wish I was there!". Add comments, including header. HELP PLEASE ASAP public...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT