简体   繁体   English

ASP.Net MVC,使用javascript提交表单

[英]ASP.Net MVC, Submit a form using javascript

I have a form on one of my ASP.Net MVC views that I created using the following code 我在我使用以下代码创建的一个ASP.Net MVC视图上有一个表单

 <% 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? 我现在正在尝试编写一个javascript函数来提交表单,这可能不知道表单名称吗?

Thanks 谢谢

You can use jquery to submit the form: 您可以使用jquery提交表单:

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

(the last part is for htmlAttributes parameter) (最后一部分是针对htmlAttributes参数)

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). 并且不要忘记包含mvc附带的jquery-1.2.6.js(或使用更高版本)。

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: 如果你想在没有命名表单的情况下使用jQuery,并且页面上只有一个表单,你可以在页面中添加这样的链接:

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

And then add this jQuery which will wire up the link to submit every form: 然后添加这个jQuery,它将连接链接以提交每个表单:

$(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 .. 说,你可能想提交多个表格..

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>

This simple solution submit the Ajax form without post-back 这个简单的解决方案提交Ajax表单而无需回发

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

Works in IE and Firefox. 适用于IE和Firefox。

If you need to set name of the form, use object htmlAttributes parameter of BeginForm method. 如果需要设置表单的名称,请使用BeginForm方法的object htmlAttributes参数。

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

For submitting forms through javascript, check out this post . 要通过javascript提交表单,请查看此帖子 Might be useful. 可能有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM