Pat Long - Munkii Yebee
Pat Long - Munkii Yebee

Reputation: 3629

ASP.NET control rendering HTML attributes

I have a custom control in an ASP.NET Web Forms project that inherits from System.Web.UI.Control.

I want to add attributes in the markup that to not correspond to properties of that control e.g.

<myControls:Hyperlink runat=server custom-client-side-attr="1"></<myControls:Hyperlink>

The problem I am having is that the exception

Type 'myControls.Hyperlink' does not have a public property named 'custom-client-side-attr'.

I have tried PersistChildren(false), but that does not fix it. It has been a while since I have been in the depths of ASP.NET Web Forms and cannot remember how this is done.

Upvotes: 1

Views: 2288

Answers (3)

Terry
Terry

Reputation: 1992

If your custom control derives from WebControl it seems to work as you want.

Upvotes: 0

afzalulh
afzalulh

Reputation: 7943

If you want an attribute like this, you have to create a property in for the user control. You may use viewstate or hidden control to keep the property persistent. Your code may look something like this:

public string  custom_client_side_attr 
{
    get {
        if (ViewState["custom_client_side_attr"] != null)
        {
            return ViewState["custom_client_side_attr"].ToString();
        }
        return string.Empty;
    }
    set
    {
        ViewState["custom_client_side_attr"] = value;
        //set custom atribute for the hyperlink here
    }
}

And access the property through markup:

<myControls:Hyperlink id="myCustomControl" runat=server custom_client_side_attr="1"></<myControls:Hyperlink>

or in the code:

myCustomControl.custom_client_side_attr="1";

Upvotes: 0

Joe Enos
Joe Enos

Reputation: 40383

You have to add those in server-code:

hl1.Attributes["custom-client-side-attr"] = "1";

You can still do it in the markup - you'd have to do it prior to the the declaration:

<% hl1.Attributes["custom-client-side-attr"] = "1"; %>
<myControls:Hyperlink ID="hl1" runat=server custom-client-side-attr="1"></<myControls:Hyperlink>

Upvotes: 4

Related Questions