Many devs do this:
public void foo() {
if (flag) {
// do stuff
}
}
I prefer to "return early", and so do this instead:
public void foo() {
if (!flag) return;
// do stuff
}
In an ASP.NET-MVC Razor view, what is the correct way to abort/skip/cancel rendering of a view/partialview? For example how do I convert this:
@if (flag) {
// do stuff
}
to something like this:
@if (!flag) { /* what do I do here to abort/skip/cancel the rendering? */ }
// do stuff
I've tried using return
and playing with the Request
, but am unsure how this affects the process. What is the correct way to do this?
As I mentioned above, you can simply issue a
return
.I recall cshtml files are compiled at runtime, which includes all inline code as well as the static html. That means that in theory, I'd expect any code to be left as-is and not transformed in any way.
So if you do this:
It works as expected (well for me at least). I just wanted to know if this leads to any unintended side-effects.
If with "abort" you mean you want to exclude something according to that flag then you have nothing to do, just use
if
to delimit such sections (eventually it may even be from that line to the end of file). Like this:Quickly it'll become hard to understand so you may use partial views for that (especially if blocks you have to include/exclude are big):
If you need to drop/skip/cancel page creation (for example to redirect to another page or to display something completely different), like this:
Then you're doing that check in the wrong place. Do it in your controller, it'll pick right view and views won't be aware of such logic:
Why not?
To summarize:
There is not a correcty way because you must not do it. Code in view has to render the page, it has not to decide which page should be sent to client. If you're doing anything else then you're using MVC as it shouldn't be used, it's just not correct.