How to update a div with Ajax.BeginForm AND execute a javascript function?

后端 未结 2 835
南笙
南笙 2020-12-16 19:28

I am updating a div with a partial view by using something like this:

<% using (Ajax.BeginForm(\"Action\", \"Controller\",
               new { id=Model.i         


        
相关标签:
2条回答
  • 2020-12-16 19:53

    Any reason for not doing it the right way (after all we are in 2010)? Dump MS AJAX where it belongs along with all the Ajax.* helpers which depend on it and write proper code. While using MS AJAX in classic webforms could have been justified because of the UpdatePanels, etc... doing it in a new ASP.NET MVC application today, especially after Microsoft have fully embraced jQuery, seems like a bad idea.

    So after the rant here's my recommendation:

    <% using (Html.BeginForm("Action", "Controller", new { id = Model.id }) { %>
    

    and then attach the submit handler unobtrusively using jquery in a separate file:

    $(function() {
        $('form').submit(function() {
            $.ajax({
                url: this.action,
                type: this.method,
                success: function(result) {
                    // feel free to execute any code 
                    // in the success callback
                    $('#result').html(result);
                }
            });
            return false;
        });
    });
    

    or using the excellent jquery form plugin:

    $(function() {
        $('form').ajaxForm(function(result) {
            // feel free to execute any code 
            // in the success callback
            $('#result').html(result);
        });
    });
    

    Benefits of this approach:

    • Unobtrusive
    • Clear separation between markup and javascript
    • Caching javascript files and decreasing bandwidth usage

    Bonus benefit: no headaches.

    0 讨论(0)
  • 2020-12-16 19:53

    I kept looking around and found the answer here:

    Assign a Javascript function to AjaxOptions OnSuccess property raise an error - ASP.NET MVC (with the answer that was not selected)

    Quoting Atzu

    If you have to pass any parameter to the OnSuccess event you may have to write the funcion in this way.

    OnSuccess = "function(){exampleFunction('" + param1 + "');}
    

    and it worked for me!

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