In ASP.Net MVC, how can you use TryUpdateModel to update from a specific object
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
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.
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)
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.
精彩评论