javascript 根据asp GridView列中的值显示图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4862470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:08:53  来源:igfitidea点击:

Display image based on a value in asp GridView column

c#javascriptasp.netgridview

提问by pavanred

I have a gridview and one of the template fields is an asp image server tag. I want to display an image in this gridview but based on the value that I obtain on databind.

我有一个 gridview,其中一个模板字段是一个 asp 图像服务器标记。我想在这个 gridview 中显示一个图像,但基于我在数据绑定上获得的值。

So, every row can have a different values and based on these values I need to display different images. I tried to call a javascript function GetImage() and pass the value that I obtain on databind to this function. But, I cannot get this to work.

因此,每一行都可以有不同的值,我需要根据这些值显示不同的图像。我试图调用一个 javascript 函数 GetImage() 并将我在数据绑定上获得的值传递给这个函数。但是,我无法让它发挥作用。

 <Columns>
      <asp:TemplateField HeaderText="<%$Resources:LocalizedText,LabelStatus%>">
           <ItemTemplate>
                <asp:Image ID="imgStatus" runat="server" CssClass="label" src="GetImage(<%#Eval(<%# Bind("Status_value")  %>) %>)"/>
           </ItemTemplate>
      </asp:TemplateField>
  </Columns>

Javascript function -

Javascript 函数 -

function GetImage(value)
{
    if (value == 1)
    {
        return "../Images/act_green.gif";
    }
    else
    {
        return "../Images/act_red.gif";
    }
}

What am I doing wrong here? And, how can I fix it? Thanks

我在这里做错了什么?而且,我该如何解决?谢谢

回答by NakedBrunch

Unless you have more needs that you haven't mentioned, there is no need to use Javascript and you might as well do everything on the server.

除非你有更多你没有提到的需求,否则没有必要使用Javascript,你也可以在服务器上做所有事情。

Change your asp:image tag to the following:

将您的 asp:image 标签更改为以下内容:

<asp:Image ID="imgStatus" runat="server" CssClass="label" ImageURL='<%# GetImage((int)Eval("Status_Value")) %>' />

In your code-behind, place the following:

在您的代码隐藏中,放置以下内容:

public static string GetImage(int value)
{
    if (value == 1)
    { 
        return "../Images/act_green.gif";
    }
    else
    {
        return "../Images/act_red.jpg";
    }
}

And you're done.

你已经完成了。

回答by msms

Your GetImagefunction is not executed.

您的GetImage函数未执行。

See: IMG SRC tags and JavaScript

请参阅: IMG SRC 标签和 JavaScript



Server side code can return the path to the image without using JS.

服务端代码可以不使用JS返回图片的路径。