Keep you MVC Razor view DRY!

Always keep your view DRY (do not repeat). Suppose your website has any of the following,

  • Top menu
  • Left menu
  • Right menu

Or you have some HTML which is repeated in different view, then you could use the following,

@Html.Partial(“ViewFile”)
Renders the “ViewFile” view to an MvcHtmlString. It follows the standard rules for view lookup (i.e. check current directory, then check the Shared directory).

@Html.RenderPartial(“ViewFile”)
Does the same as Html.Partial(), except that it writes its output directly to the response stream. This is more efficient, because the view content is not buffered in memory. However, because the method does not return any output, @Html.RenderPartial(“MyView”) won’t work. You have to wrap the call in a code block instead: @{Html.RenderPartial(“ViewFile”);}.

@RenderPage(“ViewFile.cshtml”)
Renders the specified view (identified by path and file name rather than by view name) directly to the response stream, like Html.RenderPartial(). However, it seems to always use the current view’s model as the model for “ViewFile.cshtml”.

I prefer using @RenderPage(“ViewFile.cshtml”) only because the syntax is easier and it is more readable. If you are using MVC Area RenderPage by default will look into the View and Shared folder of the Area. If you want to point it to the common View folder in the root, then you have to mention the path. See example below.

@RenderPage(“~/Views/Shared/ViewFile.cshtml”)

References,

Introducing “Razor” – a new view engine for ASP.NET

ASP.NET MVC 3: Layouts and Sections with Razor

Advertisements

Diganta Kumar has architected and developed software for more than a decade for a wide range of industries and development platforms and over the years has filled many roles including program manager, founder, developer, architect, team lead, mentor and project manager. Diganta is founder of two online IT businesses. He is a certified AWS Solutions Architect, certified Professional Scrum Master (PSM I), certified Professional Scrum Developer (PSD I) and ITIL Certified. He has presented at Microsoft Tech.Ed, Microsoft AppFest and Ark Group Intranet conference. He attends AWS Seattle Official Events, Seattle AWS Architects-Engineers, and AWS Cloud Commerce user groups. He likes to help, mentor and manage software development teams to improve and produce great software. He currently work as a Senior Technical Program Manager for Amazon Web Services.

Tagged with:
Posted in MVC

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s