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 is an experienced Technical Program Manager with a passion for technology. He has architected and developed software for more than a decade for a broad range of industries. Diganta is a founder of two online IT businesses. He is a certified AWS Solutions Architect, AWS Certified Developer, Professional Scrum Master (PSM I), Professional Scrum Developer (PSD I) and ITIL Certified. He has presented at Microsoft Tech.Ed, Microsoft AppFest and Ark Group Intranet conference in the past. He attends AWS Seattle Official Events and Seattle AWS Architects-Engineers. He likes to help, mentor, and manage software development teams to improve and produce great software.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s