Making Views Serve Two Roles in ASP.NET Core
I hate creating two or more Views that share a lot of HTML because it doubles my maintenance burden by forcing me to keep the two Views in sync. The usual reason I'm doing this is because I have single page that's supporting two user roles and I need to suppress or include some HTML based on the current user's authorization level.
While I try to avoid adding code to a View because I can't automate testing that code, I've been known to put code in Views to conditionally generate HTML to support multiple roles in a single View. The logic is usually pretty simple (a call to some IsInRole method), but it's mixed in and scattered through the HTML that makes up the View.
ASP.NET Core gives me a new tool to use that allows me to tailor a single View for multiple purposes while centralizing my code: The IgnoreSection method. The IgnoreSection method, in a View, allows me to tell the layout View to not pick up a specific section.
For example, I can now put all my command buttons in a section of my View, like this:
@section UpdateButtons {
<input type="submit" value="Update" name="Update"/>
}
Presumably, the layout View used by this View would incorporate the section into the page with a line like this:
@RenderSection("UpdateButtons", false)
But I want this View to be used both by guests (who aren't allowed to update data) and employees (who are). In ASP.NET Core, I can now suppress the section from being displayed by the layout View by passing the name of the section to the IgnoreSection method.
For example, this code in my View ensures that the UpdateButtons section won't be sent to the user if the user is in the "guest" role:
@if (User.IsInRole("guest")) {
@IgnoreSection("UpdateButtons")
}
What I like about this is that I can put this logic in the code block at the top of my View instead of scattering it throughout my View. I can also now control what each user sees just by moving HTML in and out of the appropriate sections or by adding and removing sections in my if statement.
There's also a new IgnoreBody method that suppresses a layout View's RenderBody method, but I'm not clear when I'd want to use that. You may have a better imagination than I do, of course.
Posted by Peter Vogel on 05/31/2019