对于“动态”属性,C# .NET 4 中 PHP 的 isset 等效项是什么?物体?
我目前正在使用 MVC 3,其中使用 ViewBag。我想测试 ViewBag 的属性之一是否已分配。我知道在 PHP 中你可以做 isset(variable),但是 .NET 4 中有类似的东西吗?
场景是我正在制作一个嵌套布局,它通过 ViewBag 获取部分标题和部分副标题。它们由分隔符分隔,并且副标题是可选的。如果未设置子标题,我不想显示分隔符。
这就是我想象的 isset 将被 .NET 4 等效项取代的情况。
@section header
{
<h2>@ViewBag.SectionTitle</h2>
@if(isset(ViewBag.SectionSubTitle))
{
<div id="section-title-seperator"> - </div><h3>@ViewBag.SectionSubTitle</h3>
}
}
除了直接回答我的问题之外,我还愿意接受替代解决方案(以防我滥用 ViewBag)。
提前致谢。
I am working with MVC 3 at the moment where I use the ViewBag. I would like to test if one of the properties of the ViewBag has been assigned. I know in PHP you could do isset(variable), but is there something similar in .NET 4?
The scenario is that I am making a nested layout which takes a section title and a section subtitle through the ViewBag. They are seperated by a seperator and the sub title is optional. I don't want to display the seperator if the sub title is not set.
This is how I imagine it where isset would be replaced by the .NET 4 equivelant.
@section header
{
<h2>@ViewBag.SectionTitle</h2>
@if(isset(ViewBag.SectionSubTitle))
{
<div id="section-title-seperator"> - </div><h3>@ViewBag.SectionSubTitle</h3>
}
}
Next to the direct answer to my question, I'm also open to alternate solutions (in case I'm abusing the ViewBag).
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以像这样检查它是否为
null
:@if(ViewBag.SectionSubTitle != null)
。PHP 中的 isset() 实际上只是检查是否存在值。从手册:
您还可以使用
ViewDataDictionary.ContainsKey
在您的ViewData
属性上。因为ViewData["SectionSubTitle"]
等同于ViewBag.SectionSubTitle
所以在这种情况下你可以这样做:@if(ViewData.ContainsKey("SectionSubTitle"))
You can check if it is
null
like this:@if(ViewBag.SectionSubTitle != null)
.isset()
in PHP actually just checks if there is a value present. From the manual:You can also use
ViewDataDictionary.ContainsKey
on yourViewData
property. BecauseViewData["SectionSubTitle"]
is equavilient toViewBag.SectionSubTitle
so in this case you could do:@if(ViewData.ContainsKey("SectionSubTitle"))