Babak Fakhriloo
Babak Fakhriloo

Reputation: 2126

unwanted multiple ajax request to an action in asp.net mvc

I am developing an asp.net mvc application and have ajax calls on my page. Here is a form which I load by ajax call to page :

The form is located in a partial view

<div id="CreateCultureArea">
 <% 
        using (Ajax.BeginForm("CreateCulture", "Admin", new AjaxOptions() { OnSuccess = "handleCreateCulture" }))
        { %>
.....

<% } %>
</div>

Code Updated

The following script is located in a view :

<a href="#" class="CreateCulture" id="">Create Culture</a>

<script type="text/javascript">

        $('.CreateCulture').live('click', function (e) {
            e.preventDefault();
            var idval = this.id;
            $.ajax({
                url: "/Admin/CreateCulture",
                dataType: 'html',
                data: { id: idval },
                success: function (mydata) {

                    $("#CultureContentArea").empty();
                    $("#CultureContentArea").empty().hide().append(mydata).fadeIn(2000);

                    $("form").removeData("validator");
                    $("form").removeData("unobtrusiveValidation");
                    $.validator.unobtrusive.parse("form");

                },
                type: "GET"
            });
            return false;
        })
    </script>

When users click on a link with CreateCulture class, the form is loaded to page. But as I saw the requests in firebug, it calls the action multiple times. I read similar posts like mine on stackoverflow.com and most of them suggested removing repetitive "jquery.unobtrusive-ajax.min.js" calss in page, but as I saw the output page I only see on link to the "jquery.unobtrusive-ajax.min.js" script.

Upvotes: 1

Views: 2630

Answers (3)

sadeghhp
sadeghhp

Reputation: 702

Make sure that you have not multiple .js refrence in page

<script src='/Scripts/jquery.unobtrusive-ajax.min.js'></script>
<script src="/Scripts/jquery.validate.min.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>

Upvotes: 1

Babak Fakhriloo
Babak Fakhriloo

Reputation: 2126

The problem was that I put some scripts in partial view and each time it duplicated by loading this. So I put the scripts all in on page and problem solved.

Upvotes: 0

Ethan Brown
Ethan Brown

Reputation: 27282

The problem is that @Ajax.BeginForm emits a form that has the attribute data-ajax="true". In the unobtrusive AJAX script (see the non-minified version and look for calls to asyncRequest). So by calling $.ajax yourself, you are repeating the work of @Ajax.BeginForm. Just take out your call to $.ajax and you'll see your action get called only once.

If you need to take action after the AJAX call completes, set the OnComplete property of AjaxOptions in your call to Ajax.BeginForm.

Upvotes: 3

Related Questions