I would like to do something like this:
[HttpPost]
public JsonResult Submit(Person UpdatedPerson)
{
//Find the original Person that the model was bound against
//Update the collection's reference to reflect the changes
//from the posted model version
Person original = PersonCollection
.SingleOrDefault(p=>p.Id == UpdatedPerson.Id);
if(original!=null)
{
//update the value from PersonCollection
//doesn't work, of course
original = UpdatedPerson;
}
}
I'm currently doing this:
[HttpPost]
public JsonResult Submit(Person UpdatedPerson)
{
//Find the index into PersonCollection for the original
//model bound object, use the index to directly mutate the
//PersonCollection collection
int refIndex = -1;
for(int i=0;i<PersonCollection.Length;i++)
{
if(PersonCollection[i].Id == UpdatedPerson.Id)
{
refIndex = i;
break;
}
}
if(refIndex >= 0)
{
PersonCollection[refIndex] = UpdatedPerson;
}
}
It feels like I'm missing something simple here, it shouldn't be so much trouble to accomplish what I'm after.
What is the best practice way to do this sort of stuff?
When you do this:
original = UpdatedPerson;
you are just assigning the reference to original, thus original now points to the same object that UpdatedPerson points to. and that is why you are losing the reference value for the object that you have retrieved from the collection.
Try assigning the individual fields instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With