[英]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語句將使腳本崩潰。 我想念什么或做錯什么?
謝謝你的幫助
嘗試更換
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.