views:

3469

answers:

5

I have a form on one of my ASP.Net MVC views that I created using the following code

 <% using (Html.BeginForm(null, null, FormMethod.Post))

Using this code I have no control as far as I am aware of setting the name of the form. I'm now trying to write a javascript function to submit the form, is this possible without knowing the forms name?

Thanks

+9  A: 

You can use jquery to submit the form:

<% using (Html.BeginForm(null, null, FormMethod.Post), new { id = "myForm"})

(the last part is for htmlAttributes parameter)

just do this:

$("#myForm").submit();

and do not forget to include jquery-1.2.6.js that comes with mvc (or use a higher version).

Serhat Özgel
I love how easy MVC makes things like this.
Bennor McCarthy
A: 

If you have only one form on that page, you can access the form by using:

document.forms[0].

So you could add a link:

<a href="javascript:document.forms[0].submit()">submit form</a>
jao
A: 

If you need to set name of the form, use object htmlAttributes parameter of BeginForm method.

<% using 
  (Html.BeginForm(null, null, FormMethod.Post,
     new {name="MySuperForm"})) %>

For submitting forms through javascript, check out this post. Might be useful.

Arnis L.
+3  A: 

The accepted answer is slightly wrong. The bracket shouldn't be closed before the html parameters

<% using (Html.BeginForm(null, null, FormMethod.Post, new { id="myForm"})) { %>
    //code here
<% } %>

and then:

$("#myForm").submit();
ajbeaven
A: 

This simple solution submit the Ajax form without post-back

<a href="#" onclick="$('#sbmt').trigger('click'); return false">Generate</a>
<input id="sbmt" type="submit" style="visibility: hidden" />

Works in IE and Firefox.

Alvaroma