How to call UserControl javascript when parent page submits to server?
net usercontrol located on on my aspx page. In the usercontrol there is a javascript function that I would like to fire everytime the page that contains the usercontrol submits to the server. (directly before this happens) Ideally I prefer to not have to write any code in the parent to make this happen, but I am not sure what the usercontrol may be capable of at this time. Can the usercontrol know that the page is submitting to the server and fire the function before this happens? Is there some sort of event that takes place here?
Is this possible? And is my descripti开发者_C百科on clear?
Thanks!
you can add a client side event handler for the form's submit
event. you can generate your javascript when Page_Load
is called in the user control and use Page.ClientScript.RegisterStartupScript
to add it to the page.
string key = "submitscript";
System.Text.StringBuilder script = new System.Text.StringBuilder();
script.Append("function mySubmitHandler(e) { \n");
script.Append(" // TODO my javascript here \n");
script.Append(" alert('derp'); \n");
script.Append("} \n");
script.AppendFormat("var f = document.getElementById('{0}'); \n", Page.Form.ClientID);
script.Append("if(f.addEventListener){\n");
script.Append(" f.addEventListener('submit', mySubmitHandler, false); \n");
script.Append("} else { \n");
script.Append(" f.attachEvent('onsubmit', mySubmitHandler); \n");
script.Append("} \n");
Page.ClientScript.RegisterStartupScript(this.GetType(), key, script.ToString(), true);
the script will only be added once for each combination of the type
and key
parameters, so you can have multiple user controls on the page and this script will only be added once.
Postback is a server-side event. On the client-side the page is just getting loaded again... So if you really want to write client-side script (be it in the page or a user control) for the postbacks, I would suggest you send down a hidden input or something as an indicator of whether or not it is a postback. Like:
Markup:
<asp:HiddenField ID="postBackFlag" runat="server" Value="false" />
Server side:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If IsPostBack Then
Me.postBackFlag.Value = "true"
End If
End Sub
Client side:
$(document).ready(function() {
if ($('input[id$=_postBackFlag]').val() === 'true') {
//do stuff
}
});
精彩评论