I have a plans list, or whatever it is, and I don't want any of them to be deleted. That's why when someone choose the "edit" option - I actually want to add a new plan with the same references, but just a new ID. Then, I don't care at all what changes will be made in it in the edit view (which is in fact the create view).
I use the same view whether it create new or edit, but the only difference is that if the action get a plan - I understand it is not create new but edit and then I want to display in the create view all the "edited" plan parameters, and if there isn't any plan (if the action does not get any plan) - I understand it's a totaly new plan (someone choose the "Create new" option), and then I want to display the same view - with blank fields.
Here is my code:
public ActionResult CreatePlan(Plan? plan)
{
if (plan == null)
{
return View();
}
else
{
Plan oldPlan = db.PlanSet.Single(p => p.Id == plan.Value.Id);
return View(oldPlan);
}
}
Currently, as you can see, if the action does get an object - it lets me edit the old plan.
How can I duplicate it so any change that will be made in the view - will be saved with another plan ID??? Hope I made myself clear and am happy to get some help !
For my question I didn't need to use something complicated at all.
All I needed to to is to create two get actions, one with blank fields and another with fields full with the edited object.
the two views send their parameters to the same post action, that gets the sent object and add it to the database. when I write:
db.PlanSet.AddObject(plan);
-it automatically adds the same object with new Id, without removing or changing the original object.Good Luck!!
I think what you want is: Object.MemberwiseClone().
Object.MemberwiseClone() creates a shallow copy of an object, i.e. it creates a new object and copies the references from the old object (of course, value types are duplicated).
Now, since MemberwiseClone is actually protected, you have to do something like:
give your
Plan
class a copy constructor and instead of returningView(oldPlan)
returnView(Plan(oldPlan))