在asp.net中更改img src

And*_*sti 0 .net html c# asp.net

所以我的数据库中有一个bool列,表示访问者是否是"Inhouse".如果值是,true我希望img src为:const string checkedIn = "/Images/Icons/Visitor-checkedin-16x16.png";if false,我希望它是另一个src.而且,如果访客尚未访问,"内部"应该是falseAND"预期到期"日期还没有.这是我的代码:

C#:

public string GetImageUrl(string inhouse, DateTime expectedArrival)
{
    const string checkedIn = "/Images/Icons/Visitor-checkedin-16x16.png";
    const string checkedOut = "/Images/Icons/Visitor-checkedout-16x16.png";
    const string notArrived = "/Images/Icons/Visitor-notarrived-16x16.png";

    if (ToBool(inhouse))
    {
        inhouse = checkedIn;
    }

    else if (ToBool(inhouse) == false && expectedArrival.AddDays(0) <= DateTime.Now)
    {
        inhouse = notArrived;
    }

    else
    {
        inhouse = checkedOut;
    }

    return inhouse;
}

private static bool ToBool(string value, bool defaultValue = false)
{
    bool result;
    return bool.TryParse(value, out result)
        ? result
        : defaultValue;
}
Run Code Online (Sandbox Code Playgroud)

ASPX:

<asp:Repeater runat="server" OnItemDataBound="rptVisitedItem_OnItemDataBound" OnItemCommand="rptVisitedItem_OnItemCommand" ID="rptVisitedItem">
     <ItemTemplate>
        <tr>
            <td>
                <img src='<%# GetImageUrl(Eval("Inhouse").ToString(), Convert.ToDateTime(Eval("ExpectedArrival"))) %>'alt="" class="statusIcon" />
            </td>
        </tr>
    </ItemTemplate>
</asp:Repeater>
Run Code Online (Sandbox Code Playgroud)

我哪里做错了?我只得到一张图像来显示atm.

ADy*_*son 5

有几个明显的问题需要清理:

1)假设在中继器原来的"点播"的变量是BOOL,然后将其转换成字符串,然后将其转换回一个bool是没有意义的,并已引起一个问题,因为你的ToBool方法不正确.

的TryParse返回true如果转换过程成功,并false如果没有(总阅读手册!https://msdn.microsoft.com/en-us/library/system.boolean.tryparse(v=vs.110).aspx).包含转换的bool实际值result,您不从该方法返回.相反,您将返回成功值.如果你的转换总是成功,那么ToBool总是返回true,这就是为什么你总是得到相同的图像.

2)你通过赋予它两个含义来滥用内部变量 - 首先它是一个bool来说明内部是否有内容,然后它是一个包含图像URL的字符串.它不应该是两者兼而有之.变量应该有一个目的.你所做的是不好的做法,并会混淆任何阅读它的人(包括你,在一年的时间里!).做这样的事情也是一种产生意外问题的方法.

所以,在转发器中:

<%# GetImageUrl(Eval("Inhouse"), Convert.ToDateTime(Eval("ExpectedArrival"))) %>
Run Code Online (Sandbox Code Playgroud)

(另外,还有一点:.如果ExpectedArrival还不是日期时间,为什么不它应该是如果它从你的数据库来它不应该是一个字符串,如果它已经一个DateTime,没有必要把它转换).

其次,方法:

public string GetImageUrl(bool inhouse, DateTime expectedArrival)
{
    const string checkedIn = "/Images/Icons/Visitor-checkedin-16x16.png";
    const string checkedOut = "/Images/Icons/Visitor-checkedout-16x16.png";
    const string notArrived = "/Images/Icons/Visitor-notarrived-16x16.png";
    string imageUrl = null; //separate variable to hold the chosen image URL

    if (inhouse == true)
    {
        imageUrl = checkedIn;
    }
    else if (inhouse == false && expectedArrival.AddDays(0) <= DateTime.Now)
    {
        imageUrl = notArrived;
    }
    else
    {
        imageUrl = checkedOut;
    }

    return imageUrl;
}
Run Code Online (Sandbox Code Playgroud)