Venkat
Venkat

Reputation: 2186

User control in asp.net not setting the <%=value %>

I have a user control in globalsearch.aspx.

  <Menu:SRH id="NavSRH1" nItems="30" KeyWord="<% =ss %>" runat="server" ></Menu:SRH>

in globalsearch.aspx.cs i am setting the value of string "ss"

  public string ss = "";
  ss = Request.QueryString["q"]; //value is "Happy"

in the usercontrol the value of the keyword that I am getting is <%=ss%>, But i expect the value to be Happy. I was under a feeling that it will substitute the value but it is not.

Upvotes: 2

Views: 299

Answers (1)

Eugene Podskal
Eugene Podskal

Reputation: 10401

This MSDN blog tells that

  • <%# expressions can be used as properties in server-side controls. <%= expressions cannot.

And user control is more a server-side control than HTML literal, so you will have to change "<% =ss %>" into standard Single-Value Binding that could be written in a form <%# expression %> :

 "<%# ss %>"

Just do not forget to call DataBind method in your code-behind (for example in the PreRender handler or Page_Load depending on your requirements)


Well, I am not sure what the problem is, but here is some working prototype:

Page aspx:

...
<Menu:SRH runat="server" id="SRH" KeyWord="<%# ss %>"/>
...

Page code-behind:

protected void Page_Load(object sender, EventArgs e)
{
    this.ss = "Happy KeyWord";
    this.DataBind();
}

public String ss;

User control ascx:

...
<asp:Panel runat="server" BorderWidth="1" BorderColor="Black" BorderStyle="Solid"> 
    <asp:Label runat="server" Text="<%# KeyWord %>" />
    <br />
    <asp:Label runat="server" ID="label" ForeColor="Red"/>
</asp:Panel>

User control code-behind:

protected void Page_Load(object sender, EventArgs e)
{
    String text = this.KeyWord ?? "NO VALUE";
    this.label.Text = "User control load value is : " + text;
}

public String KeyWord
{
    get;
    set;
}

It outputs:

Main page Happy KeyWord
User control load value is : Main page Happy KeyWord

P.S.: Also, if you use ViewState on your page then you will have to create those properties as ViewState backed properties.

Upvotes: 2

Related Questions