How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

后端 未结 8 600
小鲜肉
小鲜肉 2020-11-30 23:20

I have a simple form created using Ajax.BeginForm:

<% using (Ajax.BeginForm(\"Update\", \"Description\", new { id = Model.Id         


        
相关标签:
8条回答
  • 2020-12-01 00:19

    Simply place normal button indide Ajax.BeginForm and on click find parent form and normal submit. Ajax form in Razor:

    @using (Ajax.BeginForm("AjaxPost", "Home", ajaxOptions))
        {        
            <div class="form-group">
                <div class="col-md-12">
    
                    <button class="btn btn-primary" role="button" type="button" onclick="submitParentForm($(this))">Submit parent from Jquery</button>
                </div>
            </div>
        }
    

    and Javascript:

    function submitParentForm(sender) {
        var $formToSubmit = $(sender).closest('form');
    
        $formToSubmit.submit();
    }
    
    0 讨论(0)
  • 2020-12-01 00:21

    Unfortunately triggering the onsubmit or submit events wont work in all browsers.

    • Works in IE and Chrome: #('form#ajaxForm')trigger('onsubmit');
    • Works in Firefox and Safari: #('form#ajaxForm')trigger('submit');

    Also, if you trigger('submit') in Chrome or IE, it causes the entire page to be posted rather than doing an AJAX behavior.

    What works for all browsers is removing the onsubmit event behavior and just calling submit() on the form itself.

    <script type="text/javascript">
    $(function() {
    
        $('form#ajaxForm').submit(function(event) { 
            eval($(this).attr('onsubmit')); return false; 
            });
    
        $('form#ajaxForm').find('a.submit-link').click( function() { 
            $'form#ajaxForm').submit();
            });
    
      }
    </script>
      <% using (Ajax.BeginForm("Update", "Description", new { id = Model.Id },
         new AjaxOptions
         {
           UpdateTargetId = "DescriptionDiv",
           HttpMethod = "post"
         }, new { id = "ajaxForm" } )) {%>
       Description:
       <%= Html.TextBox("Description", Model.Description) %><br />
       <a href="#" class="submit-link">Save</a> 
    <% } %>
    

    Also, the link doesn't have to be contained within the form in order for this to work.

    0 讨论(0)
提交回复
热议问题