Friday, September 16, 2016

Using the same view for creating and editing in ASP.NET MVC

When you use the standard pattern for ASP.NET MVC, you will generally create separate Razor Views for Creating and Editing, but a lot of applications leverage the SAME view for Creating as well as Editing.

For example, if you submit a Create screen, you may immediately want to transition to an Edit screen so that the details can be edited further.

So, how exactly do you accomplish this using ASP.NET MVC?

Basically, you have to leverage a RedirectToAction call to redirect to another method name which can handle the management of the model.  This is because you cannot have 2 different methods with the same name and the same method signature (HttpGet and HttpPost attributes are not sufficient to distinguish between Controller methods).

Then, from the new Controller Action method, you can simply redirect to the original calling method!  You can think of this in programming terms somewhat like a Recursive loop!  The only way to break out of the loop is for the user to navigate to another view through the user interface.

Therefore, you will have code similar to the following:

No comments:

Post a Comment