views:

53

answers:

2

I am following though the examples in Professional ASP.Net MVC 2 and one of the examples doesn't work for me.

[HttpPost]
public ActionResult Edit (int id, FormCollection collection)
{
    Dinner dinner = dinnerRepository.GetDinner(id);
    if (TryUpdateModel(dinner))
    {
        dinnerRepository.Save();
        return RedirectToAction("Details", new { id = dinner.DinnerID });
    }
    return View(new DinnerFormViewModel(dinner));
}

I understand that it's suppose to take the values from the FormCollection, and then update the dinner object with it, bit I don't see the collection get referenced anywhere.

Thanks for your help, I've been trying to figure this out for the past house.

+1  A: 

To address your concern of collection not being referenced anywhere.

TryUpdateModel is a base Controller class method that performs model binding. There is quite a lot involved in this process but basically it parses request values (query string, post variables, cookies etc) and matches them up to the properties of object passed to TryUpdateModel.

Strictly speaking, FormCollection parameter to the action method is not necessary. TryUpdateModel should work without it.

Igor Zevaka
+1  A: 

There are several overloads of the TryUpdateModel() method. The TryUpdateModel<TModel>(TModel model) method you are using attempts to update the model object passed in from the default IValueProvider (which is an instance of ValueProviderCollection containing instances of FormValueProvider, RouteDataValueProvider, QueryStringValueProvider, and HttpFileCollectionValueProvider).  The FormCollection type is a NameValueCollection which carries with it its own CustomModelBinderAttribute which only binds from Form data (i.e. not route data, query string, etc.) As it stands, your method isn't doing anything with this collection.

There is another overload of TryUpdateModel() that you can pass in the FormCollection (because FormCollection implements IValueProvider) as the second parameter and it would update the model from the form data (if any data was there). If your example isn't currently working though, it's likely that something else is amiss such as no data being posted in, etc. Any form data would also be obtained from the default IValueProvider, so if you aren't getting the data you expect, passing in the FormCollection instance isn't going to help. You might consider placing a break point at the start of your action method and examining the HttpContext.Request.Form collection to see what data is getting posted in.

Derek Greer