单击Javascript按钮导致多个帖子

时间:2015-03-24 15:15:23

标签: javascript jquery

我有以下脚本在对话框中呈现局部视图:

$(function () {
            $('#addressLookupBtn').click(function () {                
            $('#dialog').dialog({
                title: 'Address Lookup Tool',
                modal: true,
                width: '1200',
                height: 'auto',
                resizable: false,
                show: {
                    effect: "fade",
                    duration: 2000
                },
                hide: {
                    effect: "fade",
                    duration: 1000
                },
                open: function (event, ui) {
                    //Load the AddressLookup action which will return
                    //the partial view: _AddressLookup

                    $(this).load("@Url.Action("AddressLookup", new { evpId = Model.EvpId })");

                }
            }).dialog('open');

        });
        });

问题是,当我提交部分视图时,服务器上有2个POSTS,我认为部分视图的提交也绑定到$('#addressLookupBtn').click。谁能看到我出错的地方?

更多信息

enter image description here

部分视图

@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "updatearea" }))
{
    <div id="updatearea" class="form-group">

        <div style="width:300px; display:block; float:left;">
            @Html.TextBox("PostCode", null, new { @class = "form-control" })            
        </div>

        <div id="NewAddressLine">

            <input type="submit" value="Lookup Postcode" class="btn btn-default" />
        </div>
    </div>    

} 

3 个答案:

答案 0 :(得分:4)

看起来帖子是使用普通表单提交和jquery事件提交的。

也许将其更改为按钮(而不是提交)并仅使用jquery提交,或者删除jquery事件并仅使用普通表单提交。

根据评论 - 使用jquery ajax而不是MS ajax的示例:

剧本:

$(document).ready(function() {

  event.preventDefault(); // stop the form from submitting the normal way
  $('#MyForm').submit(function(event) {
    $.post(
        $('#MyForm').attr('action'), 
        { 'PostCode' : $('input[name=PostCode]').val() }
    )
    .done(function(data) {
        alert('Post worked, and data was returned. Parse and/or present.');
        $('#updatearea').html(data); //Replace the current contents of "updatearea" with the returned contents 
    });
  });

});

PartialView:

@using (Html.BeginForm("MyAction", "MyController", new { @id = "MyForm" }))
{
<div id="updatearea" class="form-group">

    <div style="width:300px; display:block; float:left;">
        @Html.TextBox("PostCode", null, new { @class = "form-control" })            
    </div>

    <div id="NewAddressLine">

        <input type="submit" value="Lookup Postcode" class="btn btn-default" />
    </div>
</div>    

} 

答案 1 :(得分:0)

看起来你正在调用open,并且仍然将autoOpen设置为true(默认情况下为true)。这导致open事件运行两次。尝试将autoOpen设置为false

$('#dialog').dialog({
    ...
    autoOpen: false,
    ...
});

https://api.jqueryui.com/dialog/#option-autoOpen

答案 2 :(得分:0)

事实证明除了将以下捆绑引用从_Layout移到我的Edit视图之外,我不需要更改任何内容:

@Scripts.Render("~/bundles/unobtrusive-ajax")