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 t开发者_JS百科ries 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?)
If ToColor()
is in a different namespace than your current page, you will have to reference it from the top of your aspx page.
<%@ 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>
精彩评论