简体   繁体   中英

How to call an extension function from an aspx file rather code behind file

I want to call a function that returns color from hexa representation. How to do it.

Here is my code

<asp:Label ID="Label1" runat="server" Text='<%# Eval("Status") %>' BackColor='<%# Eval("ColorCode") %>'></asp:Label>

I want to call it this way

<asp:Label ID="Label1" runat="server" Text='<%# Eval("Status") %>' BackColor='<%# Eval("ColorCode").ToString().ToColor() %>'></asp:Label>

Currently it shows an error InvalidCastException because it returns string. I have created an extension that gives Color and applies to string. How to use it here.

This function is under other namespace where the page is.

    public static Color ToColor(this string originalColor)
    {
        return ColorTranslator.FromHtml(originalColor);
    }

Here is the error If I tries to call ToColor

'string' does not contain a definition for 'ToColor' and no extension method 'ToColor' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)

如果ToColor()与当前页面位于不同的命名空间中,则必须从aspx页面的顶部引用它。

<%@ Import Namespace="ShantanuGupta" %>

Eval returns an object, so your extension method won't work as it's on string , not object .

You can either:

  • Change the extension method so that it operates on object , which is a bad idea, as not all objects are colours.
  • Add a new function to your code behind called ToColor and call that.

For example

// In codebehind
protected Color ToColor(object originalColor)
{
    return ColorTranslator.FromHtml(Convert.ToString(originalColor));
}

//in markup

<asp:Label ID="Label1" runat="server" Text='<%# Eval("Status") %>' BackColor="<%# ToColor(Eval("ColorCode")) %>"></asp:Label>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM