Helping you solve those tough coding problems!

Posting form variables that are not strongly typed with MVC Posting form variables that are not strongly typed with MVC

Published on Mar 17, 2019 by Jamie Munro

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.


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


Solution One - Passing individual variables without a class



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


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


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:


[HttpPost]
public ActionResult LogOn(FormCollection form, string returnUrl)
{
string Username = form["Username"];
string Password = form["Password"];
}


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.

Tags: ASP.NET | mvc

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP