AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1872&pId=-1
Getting Posted ASP.NET MVC Form Data
page
by Brendan Enrick
Feedback
Average Rating: 
Views (Total / Last 10 Days): 58688/ 122

Introduction

At the center of ASP.NET MVC is exactly what one would expect. ASP.NET MVC is really just built on ASP.NET Forms and that really just exists to create HTML (in the general case). I like to point this out since it helps to limit a lot of the confusion that people often have when working with ASP.NET, but this was mostly a problem with ASP.NET Forms. With MVC, a lot less is abstracted and hidden away, so the process becomes far clearer.

With forms there were false layers of state which were created and this makes a somewhat easier, although more dangerous, transition for developers with backgrounds programming with state. This actually includes most developers, because most learn to write code on client machines. On these client machines there is usually maintained state to work with, so when you transition to the stateless architecture of web development, you expect state to be there. ASP.NET was designed with a false sense of state which makes that transition easier, and it makes a lot of logic seem far simpler. With MVC a lot more control is given to the developer, but at the same time a lot of things are wired up already. By wiring a lot of things up automatically and still giving developers seams to make changes, the development is customizable and is still easy once you learn to use it.

This article is based on part of a lesson I created for a group of junior developers who know a little bit of ASP.NET and C# and have a basic understanding of the concept of the MVC pattern. In the article I cover some of the basics of working with the data obtained from forms and form controls on ASP.NET MVC pages. I discuss how to put that data into the view, as well as different ways of accessing that data in the controller. The focus of this article is not on testing or how best to work with that data once it has been obtained. The focus is on the ways in which developers can get the data using standard ASP.NET MVC methods.

Setting up the Form View

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

Setting up the Display View

Now that we have the form created we can create a page where we can display the posted results. I am again going to try to keep this as simple as possible. How to render data on a view is within the scope of another article and not this one.

We obviously need to go and create a new view, which is just an "aspx" file in the correct folder. We will later be passing data to this view so that it can be rendered as content for the user to see. This is a fairly easy process, so I will try to make things quick.

Create the View Page

First, just right click on the Home folder since we specified earlier we were going to make this action part of the Home controller. Then you will select the "Add" submenu and from within that submenu you should see "View." Click on that option.

Figure 4: Add new view context menu

From here you should get a small window to fill in the details about the view you are going to create. This is just a little helper to make the view creation a little bit faster and easier. You obviously could have just created the file by hand, but some of the common tasks are listed here and we will be taking advantage of the master page section of the Add View window.

Figure 5: Add View window

On this window we made sure to name the View something that would make sense considering the action we used earlier in our HTML form. We also selected a master page. I might have used a strongly-typed view, but in this demonstration we have not defined any classes yet. Without any classes we do not have a type to set, so there is no reason to use that feature.

Once you click the Add button, the file will be created and opened for you. Now we can start adding in our rendered content. For this simple little demo we will just write out our values that we receive on the page, so we will need to write out our "First Name," "Middle Name," and "Last Name." Before we can actually see this, we will need to create a controller. These are not the same as the pages on web forms. We need to have a controller action show us this view before we can see it.

Listing 2: Display View Markup

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
 
    <h2>DisplayUserData</h2>
    
    First Name: <%= ViewData["FirstName"] %> <br />
    Middle Name: <%= ViewData["MiddleName"] %> <br />
    Last Name: <%= ViewData["LastName"] %>
<span style='background:yellow'> </span>
</asp:Content>
Handling Data with Request.Form

For those familiar with the Request object, the answer is yes, this is the same request object. It gives us access to the values posted to the server. We will be using these to extract the information we want to display to the user and then we will be storing this in the ViewData. The ViewData is where we get access to information in the view.

To start we need to make a method in the controller because that is basically all the controller actions are. We will name it DisplayUserData1 since that is what we said the action was called from our form view. The method will return the view we want to render. In this case it is called DisplayUserData. Once we do this we should have this code.

Listing 3: Simple controller action

public ActionResult DisplayUserData1()
{
    return View("DisplayUserData");
}

Now when we go to view the page we should see the following result.

Figure 6: Empty display view

The obvious reason why everything is blank is that we tried to fill everything based on the values obtained from ViewData, but we have not actually put any data into the ViewData object. Now we need to fill some data in so we can see a better result. We need to get this data from the posted data.

We are going to use the Request object first. So we use the indexer on the Request.Form object and pass it the name of the control whose value we want to obtain. So we want to use the names of the three text boxes we used on the first view.

Listing 4: Obtaining data from the Request.Form directly

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DisplayUserData1()
{
    string firstName = Request.Form["FirstName"];
    string middleName = Request.Form["MiddleName"];
    string lastName = Request.Form["LastName"];
 
    ViewData["FirstName"= firstName;
    ViewData["MiddleName"= middleName;
    ViewData["LastName"= lastName;
 
    return View("DisplayUserData");
}

When we submit the information, we receive the following output. We see the data displayed back to us as we expect. This shows that we successfully submitted and obtained the submitted data.

Figure 7: Display view with Request.Form data

Alternate Access to the Form Data

If you do not want to use the classic method of accessing the Request object to get to the posted form data, you can instead use the new and improved "dependencies up front" way. I call it this because the dependency on the form will be shown to anyone using the controller. In this we add a method parameter to the controller action which is of type FormCollection. ASP.NET MVC will then pass the data into that parameter variable when calling the action.

This is equivalent to what you have seen using the Request.Form collection. I kept this as the alternate because the first way of seeing it is more familiar to ASP.NET developers. I prefer using this method if I need access to the FormCollection object because it keeps my dependency on the data obvious. Working with the collection in this manner also makes it easier to fake the data in the case of testing and overall makes the data more maintainable.

Handling Data with Parameter Mapping

Obviously the Request object is too complicated to be used for most of the interactions between the view and the controller. The ASP.NET MVC team of course built in some methods of obtaining data with strongly-typed access to the values posted by the form. When these values are posted back to the server they are inserted in to the controller by intelligently assigning the values based on the names given to the controls and the controller parameters. This allows MVC to pass the posted values into parameter variables used by the controller action.

To demonstrate this, we will use another controller action. This time we will use parameters to get access to our data, so we will have three parameters in our controller action this time: firsName, middleName, and lastName. We will perform our logical operations on these parameter variables.

Listing 5: Obtaining data from the parameters

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DisplayUserData2(string firstName, 
    string middleName, string lastName)
{
    ViewData["FirstName"= firstName;
    ViewData["MiddleName"= middleName;
    ViewData["LastName"= lastName;
 
    return View("DisplayUserData");
}

Notice that we now use strongly-typed parameters instead of the strings passed to the Request.Form variable. The ASP.NET MVC framework is handling the mapping of the values passed in the form data onto these controller parameter variables.

When observing the results we receive when using this controller action, we see a similar result.

Figure 8: Display view with parameter mapped data

Handling Data with Model Binders

We know that the ASP.NET MVC Framework is smart enough to translate our FirstName TextBox into the firstName string parameter in our controller action. This is some very powerful stuff that has been added into the framework. This gets better though because the framework also allows for full object mapping using model binders. This will take the individual parameters and construct a full data model object based on the data.

In our example, we have the values required for a User object. Since this object does not yet exist, we will need to create it. So to start off this section of the article, we will create a basic class which we will use to model the data.

Listing 6: Simple User data model object

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DisplayUserData3(User user)
{
    ViewData["FirstName"= user.FirstName;
    ViewData["MiddleName"= user.MiddleName;
    ViewData["LastName"= user.LastName;
 
    return View("DisplayUserData");
}

Using the model binder allows us to skip the step of assigning the parameters to our data object. Most of the time we want to work with more advanced objects than the primitive types often passed by the simple form controls. Also, the User object is very nice to just obtain. If our user object had more properties associated with it, we would be quite glad to have the one parameter as opposed to having half a dozen parameters to deal with in our controller action.

It is possible to create custom model binders to deal with more complex situations than this one. In fact one of the most powerful assets available to the savvy ASP.NET MVC developer is the ability to customize the framework to suit specific needs. There are interfaces to implement and base classes to inherit which allow for a great deal of customization. This comes in handy when using inversion of control to invert the dependencies of your code, which is very common when working with controllers in ASP.NET MVC.

Once we execute the code using this action in our HTML form, we receive the same result we did before. We obtain the same view of the data, which shows us that these methods are fairly interchangeable. There are circumstances for each.

Figure 9: Display view with model bound data

Downloads
Conclusion

Now that we know how to work with the data that is being passed to us from the HTML forms in ASP.NET MVC, we will be able to store the information as well as adjust the user experience based on this data.

Working with ASP.NET MVC is extremely easy because we are given a great deal of control that we did not previously have. We are also given many options for working with data as we were before. We had the Request.Form as well as direct access to the controls as class-level variables.

Working with controller actions' parameters gives us an easy way to obtain user data in a way which is friendly to developers attempting to read through and understand the code.

[Brendan's Blog]


Product Spotlight
Product Spotlight 

©Copyright 1998-2021 ASPAlliance.com  |  Page Processed at 2021-03-09 6:20:23 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search