Jquery – .NET MVC – Form submit causes postback instead of onSubmit javascript execution

asp.net-mvcform-submitjquery

i'm trying to submit my Ajax form using jQuery. However calling the submit() function causes the entire page to refresh. It should just execute the onSubmit part of the form (which returns false so that the page shouldn't refresh).

<%Ajax.BeginForm("AllocateAndUpdateMech", 
  New With {.Controller = "Planning", 
            .Id = Model.Id}, 
            New AjaxOptions With {
                       .LoadingElementId = "loading", 
                       .UpdateTargetId = Model.Id & "_alloc"}, 
            New With {.id = "allocate_" & Model.Id & "_" & item.UserId}
)%>
<%Html.Hidden("mechId", item.UserId)%>
<a href="javascript:void(0);" onclick="$('#<%="allocate_" & Model.Id & "_" & item.UserId %>').submit();">Allocate: <%=item.UserName%></a>
<%Html.EndForm()%>

Best Answer

If you use the HTML Ajax.BeginForm you cant just commit the form, because the form is somehow hooked up with ASP.NET MVC Ajax.

There are 3 solutions:

Easiest and best way

Use jquery $.AJAX to commit the form

Easy but strange way

Put a submit button on the form. Set it to hidden and click it by jquery.

Difficult but the answer to your question

I have seen it someplace that you can still do exactly what you describe, but it was a workaround it didnt look nice.

Here is how its done submit form sample