You are on page 1of 17

Web Engineering (CS-666/CS-723)

Mr. Aftab Khan email id: aftab@biit.edu.pk Whatsapp# 0344-8184704


Mr. Amir Rashid email id: amir@biit.edu.pk, Whatsapp# 0302-5698539

Note:
It is intimated that following Lectures will not be repeated and would be part
of mid-term& final exam as well.

(Week 4) Lecture 7-8


Objectives: Learning objectives of this lecture are

 Understanding Forms
 Form Action and Method
 Html Helpers
 Post and Get Requests in Controllers
 Arithmetic Operations

Text Book & Resources: Professional ASP.NET MVC 5 by Jon Galloway, Brad Wilson, K. Scott Allen,
David Matson

Video Links:
https://www.youtube.com/watch?v=qfVPwPtFt-A&list=PLjVp2I_4DPy_4CvU-
mdB_vfHfT8k7o18N&index=5&t=202s

https://www.youtube.com/watch?v=Zrd38uzld2o&list=PLjVp2I_4DPy_4CvU-
mdB_vfHfT8k7o18N&index=6&t=83s

HTML Form
A form is a container for input elements: buttons, checkboxes, text inputs, and more. The input elements
in a form enable a user to enter information into a page and submit information to a server. The two most
important attributes of a form tag: the action and the method attributes.

The Action Attribute


The action attribute tells a web browser where to send the information, so naturally the action contains a
URL. The URL can be relative, or in cases where you want to send information to a different application
or a different server, the action URL can also be an absolute URL. The following form tag sends a search
term (the input named q) to the Bing search page from any application:

<form action="http://www.bing.com/search">
<input name="q" type="text" />
<input type="submit" value="Search!" />
Web Engineering (CS-666/CS-723)
Mr. Aftab Khan email id: aftab@biit.edu.pk Whatsapp# 0344-8184704
Mr. Amir Rashid email id: amir@biit.edu.pk, Whatsapp# 0302-5698539
</form>

The Method Attribute


The method attribute tells the browser whether to use an HTTP POST or HTTP GET when sending the
information. You might think the default method for a form is HTTP POST. After all, you regularly
POST forms to update your profile, submit a credit card purchase, and leave comments on the funny

animal videos on YouTube. However, the default method value is “Get,” so by default a form sends an
HTTP GET request:

<form action="http://www.bing.com/search" method="get">


<input name="q" type="text" />
<input type="submit" value="Search!" />
</form>

When a user submits a form using an HTTP GET request, the browser takes the input names and values
inside the form and puts them in the query string. In other words, the preceding form would send the
browser to the following URL (assuming the user is searching for data):
http://www.bing .com/search?q=data

A POST, on the other hand, is the type of request you use to submit a credit card transaction, add an
album to a shopping cart, or change a password. A POST request generally modifies state on the server,
and repeating the request might produce undesirable effects (such as double billing). Many browsers help
a user avoid repeating a POST request.

HTML HELPERS
ASP.NET MVC provides Html Helper class which contains different methods that help you create HTML
controls programmatically. All Html Helper methods generate HTML and return the result as a string.
The final HTML is generated at runtime by these functions. The Html Helper class is designed to generate
UI and it should not be used in controllers or models.

There are different types of helper methods.

 Create inputs − Creates inputs for text boxes and buttons.


 Create links − Creates links that are based on information from the routing tables.
 Create forms − Create form tags that can post back to our action, or to post back to an action on a
different controller.

Advantages of using Inline HTML Helper in MVC 5


 It is reusable on the same view.
 It reduces the code repetition
 It is simple to create and easy to use.
 It is easy to customization the method based on the requirement.

Html Helper controls.


The following is the list of Html Helper controls.
Web Engineering (CS-666/CS-723)
Mr. Aftab Khan email id: aftab@biit.edu.pk Whatsapp# 0344-8184704
Mr. Amir Rashid email id: amir@biit.edu.pk, Whatsapp# 0302-5698539
 Html.Beginform
 Html.EndForm
 Html.Label
 Html.TextBox
 Html.TextArea
 Html.Password
 Html.DropDownList
 Html.CheckBox
 Html.RedioButton
 Html.ListBox
Web Engineering (CS-666/CS-723)
Mr. Aftab Khan email id: aftab@biit.edu.pk Whatsapp# 0344-8184704
Mr. Amir Rashid email id: amir@biit.edu.pk, Whatsapp# 0302-5698539

Html Form Helpers


Html.BeginForm is the Html Helper that is used for creating and rendering the form in HTML. This
method makes your job easier in creating form. Here, is the method to create a form using
Html.BeginForm extension method in ASP.NET MVC5.

@using Html.BeginForm("ActionMethod", "ControllerName","Get⁄Post Method"){//Form Elements}

ActionMethod – It defines which action method is look for when submit button is clicked.
ControllerName – It defines, which controller keeps the defined action method.
Get/Post Method – it defines the method you want to use to send data from form/view to controller.
Notice that the Html.BeginForm() method is called within a using statement. The using statement ensures
that the <form> tag gets closed at the end of the using block.
All from element input fields including submit button must be within the given block curly braces of
beginForm.

Example 1:
Each form contains three basic elements: a <form> element, <input> elements (which the user can type
to), and some type of a submit button.
In this example we are going to use almost all commonly used html helpers for input.
Create a new MVC Project, go to Files - > New Project -> ASP.NET Web Application and Select MVC
Template. Give a name and Click on Ok.
Web Engineering (CS-666/CS-723)
Mr. Aftab Khan email id: aftab@biit.edu.pk Whatsapp# 0344-8184704
Mr. Amir Rashid email id: amir@biit.edu.pk, Whatsapp# 0302-5698539

Controllers: HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCApp.Controllers
{
public class HomeController : Controller
{
// GET: /
Web Engineering (CS-666/CS-723)
Mr. Aftab Khan email id: aftab@biit.edu.pk Whatsapp# 0344-8184704
Mr. Amir Rashid email id: amir@biit.edu.pk, Whatsapp# 0302-5698539

public ActionResult Index()


{
return View();
}
}
}

Views: Index.cshtml

Let's use HomeController and its view 'Index.cshtml'

In the html part let's start the with Html.BeginForm

That is the main container, we will place all controls inside the tag.

@using (Html.BeginForm("Index", "Home", FormMethod.Post))


{
}

Here in Html.Beginform we are passing View name (Index), Controller name (Home) and declare
formMethod = Post Method.

If you are not passing any parameter like View name and Controller name then it will automatically call
the current controller action method having [HttpPost] attribute.

Inside the Form Let's Start with Html.Lable : @Html.Label("UserName").

This will create a Lable Named UserName, so for Creating Label we will use @Html.Lable

Next, We need Textbox for the UserName, for that we use Html.TextBox same
as @Html.TextBox("UserName").

This will Create a TextBox Named UserName.


@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<br />

@Html.Label("UserName")
@Html.TextBox("UserName")
<br />
}
Same way we will design UserPhone, UserEmail Text Fields etc.
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<br />

@Html.Label("UserName")
Web Engineering (CS-666/CS-723)
Mr. Aftab Khan email id: aftab@biit.edu.pk Whatsapp# 0344-8184704
Mr. Amir Rashid email id: amir@biit.edu.pk, Whatsapp# 0302-5698539
@Html.TextBox("UserName")
<br />

@Html.Label("UserPhone")
@Html.TextBox("UserPhone")
<br />
@Html.Label("UserEmail")

@Html.TextBox("UserEmail")
<br />
}

For Password Type Textbox We can use Html.Password : @Html.Password("UserPassword")

@Html.Label("UserPassword")
@Html.Password("UserPassword")
<br />
For Gender (Male/Female) we can use RadioButton and for that you can use Html.RadioButton as
follows
@Html.Label("M")
@Html.RadioButton("M", new { value = "Male" })
@Html.Label("F")
@Html.RadioButton("F", new { value = "Female" })

<br />
For Country selection we can use dropdown and for that we have Html.DropDownList.

Here we have to create a list for the country for that I have added below code outside of BeginForm tag.
@{
//C# code to generate list for dropdown

var MyList = new List<SelectListItem>(){


new SelectListItem(){Value="1",Text="Pak"},
new SelectListItem(){Value="2",Text="UK"}

};
}
Now Use this MyList in your Html.DropDownList as follows.
@Html.Label("UserCountry")

@Html.DropDownList("UserCountry", MyList)

@*
passing list “My List” to populate drop down with UK and Pak value..
Note: This is style to comment in Razor Code!
*@

<br />
Same way for Checkbox we use Html.CheckBox
Web Engineering (CS-666/CS-723)
Mr. Aftab Khan email id: aftab@biit.edu.pk Whatsapp# 0344-8184704
Mr. Amir Rashid email id: amir@biit.edu.pk, Whatsapp# 0302-5698539
<br />
@Html.Label("UserTerms")
@Html.CheckBox("UserTerms")
<br />

Add Submit button in the view as follows.

<input type="submit" value="Submit" />

Now run your application. It will display your html helper contols like label, textbox, rediobutton, etc.

Example 2:
Create a Form with Simple HTML Helper Class and Arithmetic Operation
Step 1: Controllers
Create an ActionResult in controller class
[HttpGet]
public ActionResult NewFormView()
{
return View();
Web Engineering (CS-666/CS-723)
Mr. Aftab Khan email id: aftab@biit.edu.pk Whatsapp# 0344-8184704
Mr. Amir Rashid email id: amir@biit.edu.pk, Whatsapp# 0302-5698539
}
[HttpPost]
public ActionResult NewFormView(int n1tb, int n2tb)
{

ViewBag.Result = n1tb + n2tb;


return View();
}
Step 2: Views
Add a View

<h1>New Calculator</h1>
@using (Html.BeginForm())
{
<b>Num 1:</b>@Html.TextBox("n1tb")<br />
<b>Num 2:</b>@Html.TextBox("n2tb")<br />
<input type="submit" value="Add"/>

}
<b>Result:</b>@ViewBag.Result
Web Engineering (CS-666/CS-723)
Mr. Aftab Khan email id: aftab@biit.edu.pk Whatsapp# 0344-8184704
Mr. Amir Rashid email id: amir@biit.edu.pk, Whatsapp# 0302-5698539

Example 3: Use of DropDownList:


DropDownList return a<select/> elements. DropDownList Allows Single item selection.
Typically, a select element serves two purposes:

 To show a list for possible options

 To show a current value for Field

Activity 1:
Create an ASP.NET MVC Web Application that can perfom a ArithmeticOperation.

Step 1: Create a new ASP.NET MVC Web application named as ArithmeticOperation

Step 2: Add a new controller class named as Arithmetic Controller.

Step 3: Create a new Action named as DDLView.

[HttpGet]
public ActionResult DDLView()
{
ViewBag.Operations = GetItems();
return View();
Web Engineering (CS-666/CS-723)
Mr. Aftab Khan email id: aftab@biit.edu.pk Whatsapp# 0344-8184704
Mr. Amir Rashid email id: amir@biit.edu.pk, Whatsapp# 0302-5698539
}

Step 4:Add a view against DDLView action. Set Template and model as empty as we don’t have
any model in our project.

<h2>Arithmetic Operations</h2>
@using (Html.BeginForm())

{
<b>Num1</b>@Html.TextBox("n1tb") <br />
<b>Num2</b>@Html.TextBox("n2tb") <br />

<b>Operation</b>@Html.DropDownList("opt",(List<SelectListItem>)ViewBag.Operations,"S
elect")
<input type="submit" value="submit" />
}
Web Engineering (CS-666/CS-723)
Mr. Aftab Khan email id: aftab@biit.edu.pk Whatsapp# 0344-8184704
Mr. Amir Rashid email id: amir@biit.edu.pk, Whatsapp# 0302-5698539
<b>Rsult</b>@ViewBag.Result
Step 5: Create a [HttpPost] Action with the same name as DDLView
[HttpPost]

public ActionResult DDLView(int n1tb, int n2tb, string opt)

int res = 0;

switch (opt)

case "Add":

res = n1tb + n2tb;

break;

case "Sub":

res = n1tb - n2tb;

break;

default:

res = 0;

break;

ViewBag.Result = res;

ViewBag.Operations = GetItems();

return View(); }

Step 6: Add a Method in Controller which returns the list of item present in the DropDownList.
private List<SelectListItem>GetItems()

List<SelectListItem> items = new List<SelectListItem>();

items.Add(new SelectListItem{Text="Add", Value="Add"});

items.Add(new SelectListItem{Text="Sub", Value="Sub"});


Web Engineering (CS-666/CS-723)
Mr. Aftab Khan email id: aftab@biit.edu.pk Whatsapp# 0344-8184704
Mr. Amir Rashid email id: amir@biit.edu.pk, Whatsapp# 0302-5698539

return items;

Controller Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ArithmeticOperationMVCApp.Controllers
{
//Start Controller Code
public class ArithmeticController : Controller
{
//
// GET: /Arithmetic/

public ActionResult Index()


{
return View();
}
Web Engineering (CS-666/CS-723)
Mr. Aftab Khan email id: aftab@biit.edu.pk Whatsapp# 0344-8184704
Mr. Amir Rashid email id: amir@biit.edu.pk, Whatsapp# 0302-5698539
[HttpGet]
public ActionResult DDLView()
{
ViewBag.Operations = GetItems();
return View();
}

[HttpPost]
public ActionResult DDLView(int n1tb, int n2tb, string opt)
{
int res = 0;
switch (opt)
{
case "Add":
res = n1tb + n2tb;
break;
case "Sub":
res = n1tb - n2tb;
break;
default:
res = 0;
break;
}
ViewBag.Result = res; // adding res into ViewBag to access res on view

//Call of GetItems() method defined below in same controller


ViewBag.Operations = GetItems();
Web Engineering (CS-666/CS-723)
Mr. Aftab Khan email id: aftab@biit.edu.pk Whatsapp# 0344-8184704
Mr. Amir Rashid email id: amir@biit.edu.pk, Whatsapp# 0302-5698539

return View();
}
private List<SelectListItem> GetItems()
{
//List to populate drop down on view
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem{Text="Add", Value="Add"});

items.Add(new SelectListItem{Text="Sub", Value="Sub"});


return items;
}
}//End Controller Code

View Code:

<h2>Arithmetic Operations</h2>

@using (Html.BeginForm())

{ // Start BeginForm Helper Block


<b>Num1</b>@Html.TextBox("n1tb") <br />

<b>Num2</b>@Html.TextBox("n2tb") <br />

<b>Operation</b>@Html.DropDownList("opt",(List<SelectListItem>)ViewBag.Operations,"Select")

<input type="submit" value="submit" />

} //End FormHelper block

<b>Result:</b>@ViewBag.
Web Engineering (CS-666/CS-723)
Mr. Aftab Khan email id: aftab@biit.edu.pk Whatsapp# 0344-8184704
Mr. Amir Rashid email id: amir@biit.edu.pk, Whatsapp# 0302-5698539

Assignment #2
Dear students read the given lectures carefully as per the course objectives mentioned on the top
and carryout the assignment as per following instructions

1. Submission Date: Sunday 22-March-2020 at 11:59 PM ; This will also count as your
Attendance for this week.

2. You must prepare handwritten Assignment with implementation in the form of project.

3. Send it to respective course teacher (after scanning it) for assessment by email only.

Calculate average and grade of marks through html helper.

 Create new C# asp.net MVC project.


 Add controller class
 Create http get request to return view
 Use html helpers to create form for the view
 Write http post request for the button percentage to calculate percentage
 Display the grade on grade label under the suitable criteria
Web Engineering (CS-666/CS-723)
Mr. Aftab Khan email id: aftab@biit.edu.pk Whatsapp# 0344-8184704
Mr. Amir Rashid email id: amir@biit.edu.pk, Whatsapp# 0302-5698539

Output on Web Browser:

Percentage Calculator:

You might also like