Posting form variables that are not strongly typed with MVC

P

In a lot of the MVC 3 examples that are available on the Internet today, they are quite typically strongly typed to a model, e.g. public ActionResult LogOn(LogOnModel model, string returnUrl).

This is extremely useful for the validation abilities and many other aspects; however, there are times when some or all of the data is not strongly typed; then what do you do? Read on for two different approaches.

There are a couple of different approaches to take:

  1. Use individual form variables in the function definition. This is typically good when you only have a couple of fields. This will actually make them strongly typed, but not too model.
  2. Use the FormCollection type. This will provide a hash of the form fields.

Before we begin, here is an example of a strongly typed HttpPost example that we will change to not be.

[code]
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
// code here
}
}
[/code]

Solution One – Passing individual variables without a class

To accomplish the first solution, the above example code could be altered as follows:

[code]
[HttpPost]
public ActionResult LogOn(string Username, string Password, string returnUrl)
{
// do some manual validation
}
[/code]

In the above example, Username and Password refer to the field names that would be assigned to the fields in the LogOn.cshtml view.

Solution Two – Using the FormCollection

To accomplish the second solution, the above example could be altered as follows:

[code]
[HttpPost]
public ActionResult LogOn(FormCollection form, string returnUrl)
{
string Username = form[“Username”];
string Password = form[“Password”];
}
[/code]

In the above example, Username and Password refer to the field names that would be assigned to the fields in the LogOn.cshtml view.

The FormCollection above can be accessed similarly to ViewData objects that are passed between views. As long as you know the field name, you can access it dynamically as seen above.

Whenever possible, I would always suggest to strongly type your code to a model because of the benefits it provides for clean validation and strongly typed views and controllers; however, in the rare instance that it simply won’t work for you – the above two solutions provide simple alternatives.

About the author

By Jamie

My Books