Reputation: 9811
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??
Upvotes: 0
Views: 2321
Reputation: 9811
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.
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
Upvotes: 0
Reputation: 97
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
Upvotes: 0
Reputation: 4099
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;";
Upvotes: 0