简体   繁体   中英

knockoutJS - ajax form submitting twice

I have a form that's being submitted twice.

I've looked through similar jQuery-related questions here and here and google groups here but haven't been able to find a solution.

Since I'm new to Knockout.js perhaps I'm missing something obvious? I'd like to understand why it's happening. Here's what I have:

the form:

<form data-bind="submit: Save">
 <div class="span11">
@foreach (var prop in ViewData.ModelMetadata.Properties)
{      
  @Html.Label(prop.PropertyName, new { @class = "attribute-label" })
  @Html.TextBox(prop.PropertyName, "", new { data_bind = "value: " + prop.PropertyName + "" })

}

</div>
<br />
<button type="submit" class="btn" data-bind="enable: IsEnabled">Update                    
</button>
</form>

the viewmodel:

var viewModel = @Html.Raw(Json.Encode(Model));

viewModel.Save = function() {            

        $.ajax({
            url: '@Url.Action("UpdateEmployee")',
            contentType: 'application/json; charset=utf-8',
            type: "POST",
            data: ko.toJSON({ employee: viewModel }),

            success: function(result) {
                //...

            },

            error: function(xhr, ajaxOptions, thrownError) {
               //...

            }
        });

    };

    $(function() {

        ko.applyBindings(viewModel);

    });

Given the code you've shown us, there is no reason why it would submit twice. What could be happening is that you have some other code that is called that is explicitly calling the Save() function which makes it appear to be submitting twice.

I wrote up a fiddle to mimic what you have shown, it does not have the same problems you are describing.

fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM