ASP.Net MVC, Submit a form using javascript

2020-02-24 09:14发布

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

5条回答
ゆ 、 Hurt°
2楼-- · 2020-02-24 09:24

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).

查看更多
家丑人穷心不美
3楼-- · 2020-02-24 09:25

If you want to use jQuery without naming the form, and you will only have one form on the page, you can just add a link like this to your page:

<a href="#" class="submitForm">Submit</a>

And then add this jQuery which will wire up the link to submit every form:

$(document).ready(function () {
    $("a.submitForm").click(function () {
        $("form").submit();
    });
});

So this is a way of doing it (the way I just did it on my site) that doesn't require you to name the form - provided you only have one. Saying that, you may want to submit multiple forms ..

查看更多
The star\"
4楼-- · 2020-02-24 09:38

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>
查看更多
Deceive 欺骗
5楼-- · 2020-02-24 09:41

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.

查看更多
祖国的老花朵
6楼-- · 2020-02-24 09:47

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.

查看更多
登录 后发表回答