The first step to getting our data from the HTML form using
the methods in ASP.NET MVC is to set up our form. To do this we need to create
a Controller action and a View.
Once we have these two pieces in place we will be able to see some form
controls at a URL in our browser.
To start, just create an ASP.NET MVC Application in Visual
Studio using the standard New Project window.
Figure 1: Creating the new project
This should create the default ASP.NET MVC template site. If
you let Visual Studio create the test project then you should have something
that looks somewhat like this in your solution explorer.
Figure 2: Default site in solution explorer
Since we already have some Views created for us in the
default site, we will start by simply modifying one of the existing ones to our
liking. We will be opening the Index view of the Home controller.
Figure 3: Index file navigation
Inside this file we could revert back to HTML form controls.
Remember that I said that eventually we are getting to HTML, so we can use the
tools given to us by MVC or we can use the standards from HTML. For this I will
use the HTML helper class to create a form and a few text boxes and I will
create a standard HTML input button.
Listing 1: View Markup
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
<% Html.BeginForm("DisplayUserData1", "Home", FormMethod.Post); %>
<h2><%=Html.Encode(ViewData["Message"])%></h2>
First Name: <%=Html.TextBox("FirstName")%><br />
Middle Name: <%=Html.TextBox("MiddleName")%><br />
Last Name: <%=Html.TextBox("LastName")%><br />
<input type="submit" value="Save" />
<% Html.EndForm();%>
</asp:Content>
Here you see that I have created an HTML form and inside of
it I have placed 3 text boxes and a standard HTML input control. I have set the
action of the form to Post to the "DisplayUserData1" action of the
"Home" controller. Normally, I would use a different controller, but
this works well for the purposes of this article. When we view this page we
will see this.
Figure 3: Form view