Sometimes it can be efficient to share the HTML between the add and edit views in your application. Here’s how:
Notice how I have created a hidden input for the model Id? That’s key! It’s also important to note that because both add and edit use the same form they both have a form action that points to “collection/edit”. I’ve seen some people have separate
ActionResult functions for both add and edit. For the most part you don’t need to do that!
Check out the controller (simplified)…
So how does that work? Well in my model I make a few decisions. Take a look at the model Save function:
This is the key line:
In this example I’m using nHibernate with the repository pattern but this technique can be applied to any pattern. If you have an ID then grab an entity and update it with new values… otherwise just create a new one.
Understanding how a programming language works is a surefire way to be a better developer. Read more.