I want to submit a s开发者_JAVA技巧imple asp.net form in jQuery
can I assume
$("form[0]").submit()
always works, cross browser?
You mean something like this
$("#aspnetForm").submit()
Something like above would work cross browser as you said
The code you pasted is cross browser too. It won't work on ANY browser so maybe that counts as cross browser :-) just a joke
No, you can't assume this. $("form[0]").submit()
will submit the first form on the page. However, you can have more than one form on an ASP.NET page, though only one of these forms can be a server-side form (with runat="server"
attribute).
If what you want is to submit the server-side form on an ASP.NET page then I think the best way would be to do it in code-behind by registering a script. It's a bit more hassle, but should always work (and when there is no server-side form it will detect it). Something like this:
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (this.Form != null)
{
string js = String.Format("$('#{0}').submit()", this.Form.ClientID);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Submit", js, true);
}
}
These will:
$("#aspnetForm").submit()
or
var theForm = document.forms['aspnetForm'];
theForm.submit()
If you know that this code will be triggered by an input
or button
element within the ASP.NET form, or if you can select a known input
or button
element within the ASP.NET form, you can use input.form.submit();
.
Usage examples
this.form.submit();
or
$("#some_input_or_button").get(0).form.submit();
Although reading the input.form
/button.form
property does not use jQuery, it is at least as cross-browser since jQuery itself does this.
Benefit: This method allows you to avoid dependence on the form ID generated by ASP.NET's internals without having to add any extra wiring server-side.
精彩评论