0

My question is quite simple, I have a website developed in Asp.Net. I wan't to pass a parameter from server (aspx file) to client (javascript file).

Lets say I have a asp:Button, and when OnClientClick event fires I want to call javascript function with parameter from the server.

Let simplify the example, and lets say this is my webpage:

<html xmlns="http://www.w3.org/1999/xhtml">
<body>
    <form id="form" runat="server">

        <div runat="server" id="divID" >div text here...</div>
        <br />

        <asp:Button runat="server" text="click1"
            OnClientClick='<%= "alert("  + this.divID.ClientID + "); return false;" %>'
            />

        <asp:Button runat="server" text="click2"
            OnClientClick="alert('<%= this.divID.ClientID %>'); return false;"
            />

    </form>
</body>
</html>

The first button throw an client side error.
The 2nd button alert the string "<%= this.divID.ClientID %>" and not the actual value.

What I'm missing??

2

3 Answers 3

0

Generate your ClientClick code in server-side code.

(BTW - you don't have IDs on your buttons...)

In Page_Load, you could put:

btn1.OnClientClick="alert('"  + this.divID.ClientID + "'); return false;";
Sign up to request clarification or add additional context in comments.

Comments

0

One could always set a hidden form field with the value on the server side. You can then just reference that hidden field in the javascript. I find it easier to do it that way than to mess with the funkiness that is ASP.net

Comments

0

OK, so I found a solution, first of all the problem is that not all attribute support server side tags (<%= %> or <%# %>). And the attribute OnClientClick don't support them. However there is a work around.

  1. Add the Button\ImageButton an ID and run on it DataBind() on the server side.
  2. Use data binding tags <%# %>

The solution will be:

aspx code:

<div runat="server" id="divID" >div text here...</div>

<asp:Button ID="btn1" runat="server" text="click1"
 OnClientClick='<%# "alert("  + this.divID.ClientID + "); return false;" %> '/>

cs code:

protected void Page_Load(object sender, EventArgs e)
{
    btn1.DataBind();
}

now after running DataBind() on this element it's possible to use server side data binding tags to pass parameters

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.