Thursday 3 January 2013

Extract key/values from FormCollection in ASP.NET MVC action method

 To avoid you from having to chase for the same information: here's how you extract key / value pairs from the FormCollection that comes as an argument in an ASP.NET MVC action method:

public ActionResult Create(FormCollection formCollection)
{

   foreach (var key in formCollection.AllKeys)
   {
      var value = formCollection[key];
      // etc.
   }

   foreach (var key in formCollection.Keys)
   {
       var value = formCollection[key.ToString()];
       // etc.
   }
}
Also, a final tip: If you find that the formCollection does not contain the key/value pairs you expected, check that 
  1. Your controls reside within the correct form (you can have more than one)
  2. Your controls have names (just having an id is not returning values in the formCollection)
Hope this helps. 

What if I don’t have SQL Express installed?


 what if I don’t have SQL Express installed?

If you don’t have SQL Express installed and running, you may have got the following error when your code tried to read or write some data:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Blah blah blah…
No problem! You can quickly switch to use the new SQL Server Compact – a lightweight, in-process database – without having to download or install anything manually. Simply add SQL Server Compact to your project by issuing the following command in the Package Manager Console:
Install-Package EFCodeFirst.SqlServerCompact
Ta da – no more external database required. Run your project again (Shift-F5) and this time it will create and connect to a file-based database (a .sdf file will appear in your ~/App_Data folder). The EFCodeFirst.SqlServerCompact package adds a file to your project called AppStart_SQLCEEntityFramework.cs, which configures the runtime to use SQL CE.
Of course you probably still want the proper version of SQL Server when you eventually deploy your application for public use, but for small applications or for learning, SQL CE is really handy.

Search...