Razor 三元表达式中的 Html 文字
我正在尝试做类似以下的事情
<div id="test">
@(
string.IsNullOrEmpty(myString)
? @:
: myString
)
</div>
上面的语法无效,我尝试了很多不同的事情但无法让它工作。
I'm trying to do something like the following
<div id="test">
@(
string.IsNullOrEmpty(myString)
? @:
: myString
)
</div>
The above syntax is invalid, I've tried a bunch of different things but can't get it working.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试以下操作:
但我建议您编写一个完成这项工作的助手,这样您就不必将您的视图变成意大利面条:
然后在您的视图中简单地:
Try the following:
But I would recommend you writing a helper that does this job so that you don't have to turn your views into spaghetti:
and then in your view simply:
你可以这样做:
或者使其内联执行:(
请注意,上述所有内容也将在一行中工作,为了清楚起见,我刚刚将它们分开)
但是OP的初衷也可以修改为工作,但这一次必须保留换行符:
注意
事实上,您只需要对运算符中的一个选项进行强制转换,而且您不必将动态作为 Func 的第一个选项,您可以给出任何东西,评估时也一样,你可以给出任何东西,只要它与 Func 的第一个参数匹配。
例如,您可以执行以下操作(我认为这是最短的版本):
如果您经常使用它,那么继承 Func 是一个好主意,
如在这种情况下[我不确定,但可能]使用常规三元运算符并将转换推迟到被调用者)作为三元运算符。
You could do:
Or to make it inline do:
(Note that all of the above will work one line as well, I have just separated them for clarity)
However the original intention of the OP can alos be modified to work, but this time line breaks must be preserved:
Note
In fact you need the cast only on one of the options in the operator, and also you don't have to give dynamic as the first option to Func, you can give just anything, and the same when evaluating you can give anything as long it matches the first argument to Func.
For example you can do the following (which I think is the shortest version):
If you use it a lot, it would be a good idea to inherit Func as in
Or one can even write a wrapper method (or even a lambda expression in which case [I am not sure but it might be possible] to use a regular ternary operator and defer the cast to the callee) for the ternary operator.
由于新功能的另一种更新方法是在视图中创建辅助函数。这样做的优点是使语法更清晰,特别是如果您要多次调用它的话。这也可以免受跨站点脚本攻击,无需调用 @Html.Encode(),因为它不依赖于 @Html.Raw()。
只需将以下内容放入最顶部的视图中即可:
然后您可以像这样使用该函数:
Another updated approach thanks to new features is to create a helper function right in the view. This has the advantage of making the syntax a little cleaner especially if you are going to be calling it more than once. This is also safe from cross site scripting attacks without the need to call @Html.Encode() since it doesn't rely on @Html.Raw().
Just put the following right into your view at the very top:
Then you can use the function like this: