最簡單的解決方案是在LB_Video下添加多個iFrame。沒有最完美的解決方案,但它的工作確定,是你可以把它簡單...
- 選擇if/else語句
- 重構與提取方法,並創建一個新的方法「CreateVideoHtml」可多次調用
- 更改「文本」 =爲「文字+ =」可以添加這麼多批次的HTML
- 加入其中()代替的SingleOrDefault()
- 添加「ToList的() '(返回所有項目)或'Take(n)'(最多取回n)
- 呼叫從一個循環的新CreateVideoHtml方法
注也有一個與你的代碼的問題 - )的SingleOrDefault(可以返回空值,所以下一行(.Source)將下降超過VG是否爲空...你需要注意可能爲空的東西!
所以......
public void YourMethod()
{
var sb = new StringBuilder();
var videoList = db.DT_Control_VideoGalleries.Where(x => x.PageControlID == int.Parse(HF_CPID.Value)).Take(3);
foreach(var video in videoList)
{
CreateVideoHtml(video);
}
foreach(var video in videoList)
{
CreateVideoHtml(video);
}
// Nothing returned from your query - CreateVideoHtml was never called!
if (LB_Video.Text == String.Empty)
{
LB_Video.Text = "No video!";
}
}
private void CreateVideoHtml(DT_Control_VideoGallery video)
{
if (video.Source.ToString() == "YouTube")
{
LB_Video.Text += "<iframe width=" + video.Width + "height=" + video.Height + "src=\"http://www.youtube.com/embed/" + video.ReferenceKey.Trim() + "frameborder=\"0\" allowfullscreen></iframe>";
}
else
{
LB_Video.Text += "<iframe width=\"" + video.Width + "\"height=\"" + video.Height + "\"frameborder=0\" src=\"http://player.vimeo.com/video/" + video.ReferenceKey.Trim() + "?title=0&byline=0\"></iframe>";
}
}
請注意,如果您在聲明使用「無功」,這解耦特定類型的代碼,意味着代碼可以圍繞更自由地移動。接下來,如果你有很多視頻,你最好使用StringBuilder(來自System.Text命名空間)。要做到這一點,調整上述如下:
public void RenderVideo()
{
var sb = new StringBuilder();
var videoList = db.DT_Control_VideoGalleries.Where(x => x.PageControlID == int.Parse(HF_CPID.Value)).Take(3);
foreach(var video in videoList)
{
// sb is passed in by reference, so we can see any changes here
CreateVideoHtml(sb, video);
}
// Nothing returned from your query - CreateVideoHtml was never called!
if (sb.Length == 0)
{
LB_Video.Text = "No video!";
}
else
{
LB_Video.Text = sb.ToString();
}
}
// this is static - all dependencies are passed in by reference
// the calling code can see the modifications to sb
// all this method does is create Html so you could unit test it
private static void CreateVideoHtml(StringBuilder sb, DT_Control_VideoGallery video)
{
if (video.Source.ToString() == "YouTube")
{
sb.Append("<iframe width=" + video.Width + "height=" + video.Height + "src=\"http://www.youtube.com/embed/" + video.ReferenceKey.Trim() + "frameborder=\"0\" allowfullscreen></iframe>");
}
else
{
sb.Append("<iframe width=\"" + video.Width + "\"height=\"" + video.Height + "\"frameborder=0\" src=\"http://player.vimeo.com/video/" + video.ReferenceKey.Trim() + "?title=0&byline=0\"></iframe>");
}
}
呈現HTML中的字符串處理代碼永遠不會是最優雅的路要走,但它會可靠地爲你工作,而它也很容易看到(從HTML )什麼已經產生,所以很容易看有無走錯了....
下重構,你可以嘗試可能是
LB_Video.Controls.Add(new VideoControl(video));
...並讓這VideoControl對包裝類的細節如何生成HTML。
好運和快樂編碼!
那麼你有'SingleOrDefault'這將意味着只有一個記錄 – V4Vendetta
從安全的角度來看,你的代碼是非常脆弱的。確保您將用戶輸入直接放入生成的html中,以便檢查用戶輸入。 – thekip