如何用c#更改html图像src

时间:2010-10-07 06:37:09

标签: c# html webforms

<img src ="~/UserControls/Vote/Images/Arrow Up.png" id = "vote-up-off" 
        runat = "server" alt ="vote up" 
class="voteupImage" style="height: 45px; width: 44px"/>

这里我想改变某些条件的图像的src,如

if ( a==4)
{
src  url  shuld be ......
}
else
{ 
src  url should be...
}

5 个答案:

答案 0 :(得分:4)

首先,您需要提供一个id名称,该名称可用作变量:

<img src="~/UserControls/Vote/Images/Arrow Up.png" 
     id="VoteUpOff" 
     runat="server" alt ="vote up" 
     class="voteupImage" 
     style="height: 45px; width: 44px"
/>

在您的代码中,您可以使用此变量:

if (someCondition)
{
    VoteUpOff.Attributes["src"] = ResolveUrl("~/UserControls/foo.png");
}

答案 1 :(得分:2)

您需要将ID更改为不带连字符的内容,但它会是

voteUpOff.Attributes["src"] = "myImage.png";

答案 2 :(得分:1)

HTML

<img src="~/UserControls/Vote/Images/Arrow Up.png" 
         id="VoteUpOff" 
         runat="server" alt ="vote up" 
         class="voteupImage" 
         style="height: 45px; width: 44px"
    />

服务器端

if (someCondition)
{
    VoteUpOff.Attributes["src"] = ResolveUrl("~/UserControls/foo.png");
}

请记住,要查看更改,您必须在UpdatePanel中放置“img”执行更改后更新UpdatePanel,如果其UpdateMode = Conditional,否则如果其属性ChildAsTriggers = True,它将自动更新

答案 3 :(得分:0)

试试这个,它为我工作

<img src="_images/<%= AssignImageURL() %>" alt="Logo" />

C#方法

protected string AssignImageURL()
{
    String ID = Convert.ToString(Session["id"]);
    ds = sq.SelectQuery("Select LogoURl from table where ID='"+ ID+"' ");
    if (Convert.ToString(ds.Tables[0].Rows[0][0]).Trim() != "")
        return Convert.ToString(ds.Tables[0].Rows[0][0]).Trim();
    else
        return "Logo.jpg";
}

答案 4 :(得分:-2)

if (someCondition)
{
    vote-up-off.Attributes["src"] = ResolveUrl("~/UserControls/pic.png");
}