Home > BTI420 ASP.NET dev, Windows > Adding HTML Forms to ASP.NET MVC web apps

Adding HTML Forms to ASP.NET MVC web apps

January 27, 2013 Leave a comment Go to comments

This document helps the new ASP.NET MVC programmer create an interactive web app that gathers and processes user input.

This document was most recently updated in January 2013.

The intended audience is students in Seneca College’s Software Development degree program.

This is the fourth in a series of five posts that enable students to get started with ASP.NET MVC web development. The five posts are:

  1. Get ready to create ASP.NET web apps
  2. Creating your first simple ASP.NET MVC web app
  3. Data persistence choices for ASP.NET MVC web apps
  4. Adding HTML Forms to ASP.NET MVC web apps
  5. Designing an ASP.NET MVC web app (version 1)


Introduction and context

In the “Creating your first…” post, you created a simple three-page web app. The user was able to navigate among the pages using HTML hyperlinks.

In this document, you will add HTML Forms to pages that need to gather and process user input.

You will also learn an important yet simple-to-implement coding pattern, called PRG, for post-redirect-get.


Example app

The “Get Started Series 2 Forms” example implements the discussion in this post.

The app has one controller (HomeController), and five views (including the Index view).

It shows you how to work with the most common HTML form elements. The app does not use any data persistence scheme. Instead, the app’s data is created and maintained in memory, and passed among the controller and views.

Forms code example


Post-Redirect-Get (PRG) coding pattern

When working with HTML forms, you must use the Post-Redirect-Get (PRG) coding pattern.

When you use the PRG pattern, your app prevents a problem where a user “refreshes” a browser page after an HTTP POST request. It also enables the browser’s “back” function to work better after the POST.

To use the pattern, simply make sure that all of the method’s code paths return a RedirectToAction() result.


More information

In an ASP.NET MVC web app, a controller method returns a view. You have seen this repeatedly in the introductory code examples.

A web browser can create an HTTP “GET” request, or a “POST” request. When there’s an HTML form element on a page (that gets delivered to a browser), submitting the form back to the web app is done with a POST request.

Public methods in a controller are, by convention, available in a GET request. The name of the method is the “action” in the URL pattern, /{controller}/{action}/{id}.

If you decorate the method with the [HttpPost] attribute, it will be available in a POST request.

Study the “…Forms” programming code example:

  1. In HomeController, locate the BasicHtml method, and the BasicHtmlPost method
  2. In the Views folder hierarchy, locate the BasicHtml.cshtml view


The BasicHtml method handles the “GET /Home/BasicHtml” request. It returns the BasicHtml.cshtml view. The view includes an HTML form; notice its action is “/Home/BasicHtmlPost”.

The BasicHtmlPost method handles the “POST /Home/BasicHtmlPost” request. Notice that the method is preceded with the [HttpPost] attribute. (Go ahead – in a browser, attempt to browse to /Home/BasicHtmlPost – you will get an error, which is expected.)

A method that handles a POST must not return a view. Instead, return a RedirectToAction() result. The response back to the browser is an HTTP 302 (to /Home/BasicHtml), which causes the browser to create a new GET request for the URL.

If you need data to flow from the POST task to the view, then you must make that happen. As you learned in the “Data persistence choices…” post/document, there are several ways to persist data. At a minimum, using TempData will work well in this programming code example. (Later examples will use Session State, and/or Application State, and/or a data store.

Study the diagram below, which illustrates the PRG pattern.


PRG pattern


Getting data TO the view

There are two commonly-used ways to pass data from the controller method to the view:

  1. ViewBag
  2. model object


In the code example, we use the ViewBag. In the near future, you will begin to use a model object, and over time, you will prefer the model object.

However, ViewBag is really easy to use. It enables you to dynamically declare and use properties of the ViewBag, without the coding ceremony of formally declaring the property (or using the dictionary item accessor syntax). For example, if you simply decide that you need a string property called “Result”, then this controller code will create and assign the data:

ViewBag.Result = “Hello, world!”;

String properties do not require any casting or conversion. For other types, including complex types or collections, you must cast or convert in a code expression in the view. Note that if you have to worry about casting/converting, you’re better off using a model object.

ViewBag is a syntax layer on ViewData. The type of ViewData is ViewDataDictionary, which is a collection of one or more items. Each item has a string key identifier, and its value can be an object of any type.

This StackOverflow post discusses ViewBag, and raises some interesting points.


Getting data FROM the view’s HTML Form

There are several ways to get user input from a browser (view), into a controller method:

  1. HTML Form
  2. URL route values (e.g. the {id} segment)
  3. Query string
  4. Other (request header, request message body, HTTP cookie, uploaded file, XmlHttpRequest, etc.)


This post/document covers HTML Forms, so we’ll focus on that.

In your controller method code, there are two common ways to get access to the values that are posted in an HTML Form:

  1. Request.Form[“name”]
  2. FormCollection object


In the first way (Request.Form), the “name” string is the name of the HTML Forms element that you wish to read from. Its type is a string, so you will have to cast/convert the value. For example:

int userInput = Convert.ToInt32(Request.Form[“textboxInput”];

In the second way (FormCollection), the method needs a parameter of type FormCollection (which is a dictionary-like type). For example:

public ActionResult AutoPost(FormCollection collection) { }

Accessing a value is done using similar syntax:

int userInput = Convert.ToInt32(collection[“textboxInput”];


Discussion – the BasicHtml and BasicMvc views

The BasicHtml and BasicMvc views are very similar:

  • The BasicHtml view uses HTML markup in the view to render the HTML elements
  • The BasicMvc view uses HTML Helpers in the view to render some HTML elements


In the design of the method + view, the programmer decided that yes, it will be using data that’s generated in an interactive session. TempData was used to persist the data. (This design and reasoning is valid for all other views in this web app, SelectLists, and AutoPost.)

That’s why the GET method code checks whether the data item is available.

In the well-documented POST method code, the form input is read/accessed, and then processed. Then, TempData is used for data persistence. Finally, a redirect, to the view’s GET action method, is performed.


Discussion – the SelectLists view

As noted in the SelectLists view, its purpose is to demonstrate the coding and configuration of commonly-used “select list” elements.

Notice that the input data from multi-select lists (the listbox and the checkbox group) is formatted as a comma-separated list of values.


Discussion – the AutoPost view

As noted in the AutoPost view, its purpose is to demonstrate the coding and configuration of form elements that raise an event when their value changes. In summary, we simply want to perform a form post/submit when this happens.

Although you can configure many elements with this behaviour, it is more common to use it with the elements in the programming code example.


Summary, and what’s next

In this post, you learned how to add HTML Forms to your views.

We also covered the Post-Redirect-Get coding pattern, and discussed ways to get data TO a view, and FROM an HTML Form.

In the next post, you will learn to design a more substantial web app, which uses a data model.


  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: