iasksillyquestions
iasksillyquestions

Reputation: 5689

Should I use the same controller and view for editing and creating models in ASP.NET MVC?

Should I use the same controller and view for editing and creating models in ASP.NET MVC, or should I create a view and controller action for creating and a view and controller action for editing?

The editing view is certainly likely to be different - it doesn't always make sense for the user interface for editing an object be the same as the view for creation,

By separating the views I will avoid lots of "if statements" to determine if I'm editing or creating...

Thoughts?

Upvotes: 1

Views: 355

Answers (2)

AndreasKnudsen
AndreasKnudsen

Reputation: 3481

AFAIK this is recommended: (Person used in example)

use one controller to handle both cases

In that controller, have four actions:

  • New()
  • Edit(int personId)
  • Create(Person p)
  • Update(Person p)

Two views, Person/New.aspx and person/Edit.aspx

the two views each contain the form that posts to their respective actions:

  • New -> Create
  • Edit -> Update

Now you have two choices, either implement the form contents twice (in each of the views) or implement the actual form in a PersonForm.ascx and use partial rendering to render the form contents.

Which way you choose to go on the last one here depends on whether the forms are to be more or less the same (go for a common control) or if they are to be way different (implement two different ones)

If it's just a matter of different layout in the new/edit forms you might want to just refer to different css files and let css handle the differences

Upvotes: 0

Robin Minto
Robin Minto

Reputation: 15367

The recommendations I've seen are suggesting that the views are separate with common elements contained within a control to stay DRY.

It seems logical to take the same approach with the controller - reuse common parts where appropriate.

This view is mirrored here How to cleanly reuse edit / new views in Asp.NET MVC as the question is very similar.

Upvotes: 2

Related Questions