powered by Slim Framework
enhanced by Nesbot.com

MVC 3: Posting form variables that are not strongly typed

Published on Nov 28, 2011 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.


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


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?




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.


Solution One


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


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.

Summary


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 | mvc3

<- jQuery: Splitting an unordered list into multiple columns  Home MVC 3: Accessing the RouteData inside of your code -> 
blog comments powered by Disqus