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?
In your first example, you make a variable declaration:
That
originalvariable is a reference.Then you assign it to some item in your list
Then later you make a call like this:
In this call, you’re updating the variable reference, not anything from the collection.
What you might want to do is something like this (Presuming Person is a class, not a struct):
but you’d have to create such a method on the person object.
Or in your second method, you could simplify from:
to