开发者

How to submit an ASP.NET MVC form using javascript and still validate on client side?

开发者 https://www.devze.com 2023-01-05 05:00 出处:网络
I have an ASP.NET MVC 2 form that is working perfectly, doing client side validation (using Data Annotations). Whenever users click on the submit button, client side validation kicks in before the for

I have an ASP.NET MVC 2 form that is working perfectly, doing client side validation (using Data Annotations). Whenever users click on the submit button, client side validation kicks in before the form is actually posted back to the server.

This is the actual code, really basic stuff:

<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm()) { %>开发者_JS百科
    <%= Html.ValidationSummary(true) %>
    <%: Html.EditorForModel() %>
    <p>
        <input type="submit" value="Save" />
    </p>
<% } %>

Now here is my problem: I want to submit the form using a button that is not inside the < FORM > < /FORM > like the one in the sample above. This button needs to be placed inside a separate < DIV > on the page that works like a toolbar for all buttons and actions in my application.

I'm able to submit the form using something like this (using jQuery):

<asp:Content ID="Content2" ContentPlaceHolderID="ToolBarContent" runat="server">
    <input type="submit" value="Save" onclick="$('#form0').submit();" />
</asp:Content>

The only problem is that this will not trigger the client side validation, as if the user was clicking in the normal submit button. The whole form is posted back, server side validation is performed and the view is rendered again showing the validation errors.

I don't want to have this regular submit button together with the form, just need to have this one in the toolbar, so is there a way to accomplish this? Having a separate button call the submit of the form while still triggering client side validation for the form?


Try this hack:

<input type="submit" value="Save" onclick="$('#dummy').click();" />

where dummy is a hidden submit button inside your form.

Also the Save button doesn't need to be a submit button if it is not placed inside a form.


Validation methods are attached to the submit event of the form, which means you should be able to call form.submit() from javascript and the submit events should still fire.


You could try jQuery's Ajax Form plugin.

http://jquery.malsup.com/form/

You can also just attach to the submit event of the form via $('#form').submit(function() { })


Try $("#yourform").validate("submit"); in case you use MicrosoftMvcValidation.js or $("#yourform").validate() if you use jquery.validate.js

0

精彩评论

暂无评论...
验证码 换一张
取 消