ASP.NET MVC 3: Share Add/edit Form With View Partials

Sometimes it can be efficient to share the HTML between the add and edit views in your application. Here’s how:




(Looks pretty much the same! Change the title, add some javascript, whatever.)




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.

Creating your first programming language is easier than you think.

Understanding how a programming language works is a surefire way to be a better developer. Read more.

Suggested Reading

written by Ryan Bosinger
Ryan is a web developer living and working in Banff Alberta. He also writes for giftsforpeoplewitheverything.com and freefoley.com.

One Response to “ASP.NET MVC 3: Share Add/edit Form With View Partials”

  1. Samuel.T says:

    Thanks for you post very useful !! :)

Leave a Reply