以下是观点:
@if (stream.StreamSourceId == 1)
{
<img class="source" src="@Url.Content("~/Public/assets/images/own3dlogo.png")" alt="" />
}
else if (stream.StreamSourceId == 2)
{
<img class="source" src="@Url.Content("~/Public/assets/images/twitchlogo.png")" alt="" />
}
基本上,我使用Model属性来确定要渲染的图像。
我知道,正确的解决方案是在名为SourceImageUrl (string)
的模型上创建属性,并将该属性用作图像的源网址。
然后我将这个条件操作转移到模型。
我的问题是,如果我使用DataAnnotations进行验证,我该怎么做呢?有什么建议吗?
public class StreamModel
{
// This is the ID that has the value of either 1 or 2.
public int StreamSourceId { get; set; }
// How can I move the logic from the view, to here, and set the value accordingly?
public string SourceImageUrl { get; set; }
}
答案 0 :(得分:1)
你能不做这样的事吗?
public string SourceImageUrl
{
get
{
switch (StreamSourceId)
{
case 1: return "~/Public/assets/images/own3dlogo.png";
case 2: return "~/Public/assets/images/twitchlogo.png";
default: return null;
}
}
}
答案 1 :(得分:1)
我建议您将逻辑移到模型中,以便您的视图与此类似
<img class="source" src="@Url.Content(stream.SourceImageUrl)" alt="" />
你的模型将是
public class Model
{
private string[] m_images;
public Model()
{
m_images = new[] {
"~/Public/assets/images/own3dlogo.png",
"~/Public/assets/images/twitchlogo.png"
};
}
public string SourceImageUrl
{
get { return m_images[StreamSourceId]; }
}
}
如果您不喜欢数组,可以使用更智能的集合替换它:Dictionary,HashSet,ecc