0

这是视图:

    @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)并将该属性用作图像的源 URL。

然后我会将这个条件操作转移到模型中。

我的问题是,如果我使用 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; }    
}
4

2 回答 2

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;
        }
    }
}
于 2012-07-05T15:35:15.003 回答
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

于 2012-07-05T15:42:30.463 回答