One of my razor views expects a model type of IEnumerable(Of Object)
.
I want to check if this collection is empty and, if so, do nothing.
One way to do this is to wrap my view code inside an If
.
@If Model.Count > 0 Then
' Lengthy HTML + Razor Code
End If
But I feel like this is ugly, so instead I tried exiting the Sub
(C# return
).
@If Model.Count = 0 Then
@<p>List is empty.</p>
Exit Sub
End If
' Lengthy HTML + Razor Code
This works and seems to achieve the same result, but code isn't wrapped in ugly If
statements.
My understanding of how a view is rendered is limited, but I'm kind of surprised that this works. Wouldn't exiting a Sub interrupt the process somehow?
Is there are inherent danger to this style? Is it ok to Exit Sub
from a view? Is it common?
Razor is parsed on the server side, before the code ever reaches the browser. It's perfectly legal and accepted to use normal VB or C# constructs such as Exit Sub
. A view file is not literally what the browser will see; rather, it is instructions for the server to use to construct the HTML that should be sent to the browser. In other languages, this might be referred to as a template or master page. Ultimately, using a construct like Exit Sub
is fine as it is handled on the server.
However there is a caviat here.... Exit Sub
will drop out from processing the current view file, causing it to never process any Razor after that statement. It will continue to process other files, but care should be taken to ensure that you do not leave dangling HTML elements with missing closures, or other HTML or JavaScript elements after the Exit Sub
call that are necessary for the page. In general, it's probably a much safer practice to use Else
rather than Exit Sub
.
An even better option would be to use a strongly typed partial view and enclose the RenderPartial()
call in the if statement.