views:

49

answers:

3

I have a controller post action that receives an IList<> as a parameter, and would like to iterate that list and TryUpdateModel for each item in the list. Like

[HttpPost]
public ActionResult SaveList(IList<Stuff> listOfStuff)
{
    // Get existing list of Stuff objects
    IList<Stuff> currentStuff = db.GetStuffList();

    // iterate over list of Stuff
    foreach (Stuff stuff in listOfStuff)
    {
        // I'd like to do something akin to this
        TryUpdateModel(currentStuff[correspondingItem_to_stuff], stuff);
    }

As you can see, I would like to be able to TryUpdateModel against each item in listOfStuff, but there is no direct way to make that call with the two Stuff objects. What is the best way of accomplishing this?

Thanks

+1  A: 

If you want currentStuff to be the same as list of stuff you just have to UpdateModel(currentStuff). UpdateModel is for copying posted http request related values values into an object and not for copying the properties of two objects.

jfar
I am not sure I understand. UpdateModel works fine for strongly typed input parameters to an action. If instead of an IList<Stuff> I pass a single Stuff, set currentStuff to a Stuff object and call UpdateModel(currentStuff) or TryUpdateModel(surrentStuff), it works fine. With the two IList objects, however, it does not.
erg39
A: 

UpdateModel and TryUpdateModel must receive a type of ValueProvider (a FormCollection for example). validate the posted object in your controller or service layer and then let your DB layer handle the add/update by using attach() or applycurrentvalues() (if your using Entity Framework for example)

Mark
I am in fact using EF. The problem with that is there is a whitelist of properties coming in from on the POST request, so if there is an error somewhere along the line to save the objects, repopulating the response view with the values the user set is not nearly as easy as using TryUpdateModel.
erg39
if the respone view must re-populate i would use a strongly typed view object (uses modelbinder) and then validate against modelstate (using data annotations) before passing to my persistence layer or returning the object back to the response view model
Mark
A: 

It looks like this is not supported directly. After some more searching I found a couple of links, the most useful of which was

Passing Controller a FormCollection and an IList

This post has a couple of other useful links in it. I ended up rolling it myself unfortunately, and using TempData as detailed here to recover in the case where saving the form data fails.

erg39