剃须刀内部的“退出子"是否值得关注? [英] Is 'Exit Sub' from within a razor view a concern?

查看:64
本文介绍了剃须刀内部的“退出子"是否值得关注?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的剃刀视图之一期望模型类型为IEnumerable(Of Object).

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.

一种方法是将我的视图代码包装在If中.

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

但是我觉得这很丑,所以我尝试退出Sub(C#return).

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

这行得通,并且似乎可以达到相同的结果,但是代码并未包裹在难看的If语句中.

This works and seems to achieve the same result, but code isn't wrapped in ugly If statements.

我对视图呈现方式的理解是有限的,但是我对此感到惊讶.退出Sub会不会以某种方式中断该过程?

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?

此样式是否存在固有的危险? Exit Sub 从视图上可以吗?这很常见吗?

推荐答案

在代码到达浏览器之前,在服务器端解析了剃刀.使用常规的VB或C#构造(例如Exit Sub)是完全合法的,并且被接受.视图文件实际上不是浏览器将看到的内容;相反,它是服务器用来构造应发送到浏览器的HTML的指令.用其他语言,这可以称为模板或母版页.最终,使用Exit Sub之类的构造就可以了,因为它是在服务器上处理的.

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.

但是在这里有一个鱼子酱....Exit Sub将退出处理当前视图文件的位置,从而导致该语句之后再也不会处理任何Razor.它将继续处理其他文件,但应注意确保您不要在页面上必要的Exit Sub调用后留下丢失的HTML元素(缺少闭包)或其他HTML或JavaScript元素.通常,使用Else而不是Exit Sub可能是更安全的做法.

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.

一个更好的选择是使用强类型的局部视图,并将RenderPartial()调用包含在if语句中.

An even better option would be to use a strongly typed partial view and enclose the RenderPartial() call in the if statement.

这篇关于剃须刀内部的“退出子"是否值得关注?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆