In my web application I have to provide a form for creating and editing. The forms for creating and for editing have minor differences, so I am thinking of doing something like this in my view:
<form>
// a lot of htnl goes here
@if (editing)
{
// some more fields shown in edit mode
}
@if(!editing)
{
// some stuff shown in create mode
}
I have always tried to not put any if
statements in my views, but this time I don’t see any other option except copying a huge portion of HTML in two places, which I don’t want to do. Is this proper “presentation logic” and are there any other options?
Presentation logic comprises the logic and calculations that are needed to present the business data in the right way for a particular view.
For complex graphical views, this can be quite complex calculations (for example, calculating the size of each pie slice and the positioning of the labels for a pie chart), but the main characteristic is that it only calculates information that is relevant for the current view and that it doesn’t modify the business data in any way.
Whether the selection of fields for edit/create mode is a proper use of presentation logic is debatable. In part it depends on the kind and amount of customization.
For example, if the difference is just a title change, or showing one or two fields as read-only in one of the modes, then it can be the right choice to have one view and select the modes dynamically.
On the other hand, my first reaction was that it should really be two different views, where the common parts are imported from a third file (similar to how commonly the header and footer are added to the views).
It seems perfectly reasonable to use an @if statement or two in a Razor view.
They added @if to Razor – it’s meant to be used.
Your code could be shortened to one @if:
@if (editing)
{
// some more fields shown in edit mode
}
else
{
// some stuff shown in create mode
}
An alternative is to use three views:
- Partial view containing the common HTML
- Create view (calls the partial view)
- Edit view (also calls the partial view)
You could check out DisplayTemplates and EditorTemplates, which are a good way of splitting read-only and editable views.
http://www.growingwiththeweb.com/2012/12/aspnet-mvc-display-and-editor-templates.html