I am doing [this tutorial][1] over at http://www.asp.net. It is written for ASP.NET MVC 1. Although most of the stuff works for MVC 3, I do have a question regarding this code:
ASP.NET MVC 1.0 (straight from the tutorial)
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "Id")] Contact contactToCreate)
{
if (!ModelState.IsValid)
return View();
try
{
_entities.AddToContactSet(contactToCreate);
_entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
ASP.NET MVC 3 (default Create action generated by MVC 3 Project, except my _entities object)
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
_entities.AddToContacts(collection); // synax error
_entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
So my question is why do we pass Contact contactToCreate in the first case, but FormCollection collection in the second?
I could easily change argument in the second example to just Contact Contact contactToCreate, but I am curious as to what is this FormCollection collection stuff? Why did MVC 3 generate it for us? If it’s possible to use FormCollection instead, how would the modified example look like?
[1]: http://www.asp.net/mvc/tutorials/iteration-1-create-the-application-cs
FormCollectionis the values entered by the user andContactis the enderlying entity that you are creating.Remember that this method is essentially called directly by the user as the result of a HTTP post and its bad practice to be blindly accepting user input without validating it. This and the fact that in real-world scenarios the values available to you in a HTTP post request don’t exactly match up to your data entity properties is probably the reason why its probably a good idea to accept a
FormCollection(or other abstracted input representing your form values) rather than directly accepting an entity in your database.Personally my modified example would look a little like this:
The
validateAndCreateContactshould validate user input and return a suitableContactobject if the input is all OK. If not it should returnnulland handle displaying a suitable error to the user (for example by setting properties on theViewData).