繁体   English   中英

C#剃须刀如果语句不起作用

[英]c# razor if statement not working

我被要求对Umbraco的网页buid进行一些更改,而我对此几乎一无所知,并且对C#非常基础。

这是代码的冒犯之处:

@foreach (DynamicNode child in root.Children)
        {
            string image = @child.GetProperty("image").Value;
            var imgURL = Model.MediaById(image).url;
            var extURL = @child.GetProperty("externalURL").Value;
            var fullURL = "http://" + extURL;

            string externalLinks = child.GetProperty("externalDocuments").Value;
            string downloadsFolderId = @child.GetProperty("downloadsFolder").Value;
            string brandName = child.GetProperty("brandName").Value;
            bool brandCheck = brandName.Contains("Generic");

            if (brandCheck == true)
            {
              string brandHeader = "<h2 class='blue' title='"+@child.GetProperty("brandName").Value+"'>"+@child.GetProperty("brandName").Value+" <span></span></h2>";
            }
            else
            {
              string brandHeader = "<h2 class='red' title='"+@child.GetProperty("brandName").Value+"'>"+@child.GetProperty("brandName").Value+" <span></span></h2>";
            }

            //Links
            <span style="display:none" id="tester" >@brandCheck</span>
            <div class="brand-container">
                @Html.Raw(brandHeader)

因此,基本上我需要检查返回的产品名称是否包含字符串“ Generic”。 如果是这样,则应用“蓝色”类,如果不应用“红色”类-听起来很容易。

字符串搜索可以正常进行,因为隐藏的@brandCheck会相应返回true或false值。 另外,如果删除if语句并定义字符串brandHeader,则将在最后一行(@ html.Raw(brandHeader))(在上面的代码中)正确生成该字符串。

显然,问题在于if语句。 我试过了:

  • if(brandCheck == true)
  • if(brandCheck === true)
  • if(brandCheck =='true')
  • if(brandCheck ==='true')
  • 如果(brandCheck)

但似乎没有任何效果,if语句将使脚本崩溃。 我想念什么或做错什么?

谢谢你的帮助

尝试更换

bool brandCheck = brandName.Contains("Generic");

if (brandCheck == true)
{
     string brandHeader = "<h2 class='blue' title='"+@child.GetProperty("brandName").Value+"'>"+@child.GetProperty("brandName").Value+" <span></span></h2>";
}
else
{
     string brandHeader = "<h2 class='red' title='"+@child.GetProperty("brandName").Value+"'>"+@child.GetProperty("brandName").Value+" <span></span></h2>";
}

string brandHeader = string.Format("<h2 class='{0}' title='"+@child.GetProperty("brandName").Value+"'>"+@child.GetProperty("brandName").Value+" <span></span></h2>", brandName.Contains("Generic") ? "blue" : "red");

这不是程序崩溃的前提,而是事实

string brandHeader 

仅在if子句内定义。

如果以后再访问它,将不再对其进行定义,从而导致脚本崩溃(换句话说:一旦离开if子句,则string brandHeader不在范围内)。

解决方法是,将

string brandHeader;

在if子句之外,而在if子句中仅通过

brandheader = < value >;

开头没有字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM