【问题标题】:Getting duplicate actions when processing in MVC controller在 MVC 控制器中处理时获取重复操作
【发布时间】:2017-12-01 04:23:51
【问题描述】:

所以我正在向我的控制器发送一个 ajax 请求进行处理。 但是当我在我的 ajax done 函数中 console.log 消息时,它会显示两个结果。

console.log 的结果是:

{"result_code":1,"result_message":"Contact tags deleted","result_output":"json"}
{"result_code":1,"result_message":"Contact tags added","result_output":"json"}

这是 ajax 请求:

$('.travelSwitch').click(function () {
        //send ajax request
        $.ajax({
            method: "POST",
            url: "@Url.Action("ProcessPreferences", "ManagePreferences")",
            data: {
                //Applies to camping category
                categoryTag: "Travel",
                //send user email for processing
                userEmailAddr: "@userEmailAddr",
                //send remove flag for processing
                removeTag: ($('#field_22Travel:checked').length) ? false : true
            }
        })
        .done(function (msg) {
            console.log(msg);
        })
    });

然后是我控制器中处理ajax请求的函数:

[HttpPost]
    public ActionResult ProcessPreferences(string categoryTag, string userEmailAddr, bool removeTag)
    { 
        string applyToTag = "TOPIC: " + categoryTag;
        string emailAddr = userEmailAddr;
        bool removeFlag = removeTag;
        var acs = new Acs("api_key", "api_url");

        Dictionary<string, string> getParameters = new Dictionary<string, string>();
        if (removeFlag == false) {
            //get parameters
            getParameters.Add("api_action", "contact_tag_add");
            getParameters.Add("api_output", "json");
        }
        else
        {
            //get parameters
            getParameters.Add("api_action", "contact_tag_remove");
            getParameters.Add("api_output", "json");
        }

        //post parameters
        Dictionary<string, string> postParameters = new Dictionary<string, string>
        {
            { "email", emailAddr },
            { "tags", applyToTag }
        };

        var response = acs.SendRequest("POST", getParameters, postParameters);

        return Content(response);
    }

因此,当处理 ajax 请求时,它会向活动的活动 api 发送请求。然后根据复选框是否选中来添加或删除标签。

注意事项 开关来自这个实现:https://www.w3schools.com/howto/howto_css_switch.asp

在页面加载时发送初始 ajax 请求以将开关设置为打开或关闭:

$.ajax({
    method: "POST",
    url: "@Url.Action("InitPreferences", "ManagePreferences")",
    data: {
        userEmailAddr: "@userEmailAddr",
        apiCallInit: true
    }
})
.done(function (msg) {
    //loop through tags
    for (i in msg.tags) {
        //console.log(msg.tags[i]);
        (msg.tags[i] == "TOPIC: Camping") ? $("#field_22Camping").attr("checked", true) : "";
        (msg.tags[i] == "TOPIC: Hiking") ? $("#field_22Hiking").attr("checked", true) : "";
        (msg.tags[i] == "TOPIC: Travel") ? $("#field_22Travel").attr("checked", true) : "";
    }
})

【问题讨论】:

    标签: c# jquery ajax asp.net-mvc api


    【解决方案1】:

    您的 ajax 函数似乎被调用了两次,并且在两次调用之间,复选框未被选中...请验证在您尝试单击元素时订阅了多少事件,这更像是一个javascript 问题而不是后端一个 imo。

    【讨论】:

    • 这是唯一一次发送ajax请求$('.travelSwitch').click(function () {});
    • 另见我的更新anwser,有一个inittail ajax请求发送到api以根据api响应设置checked属性
    • 我会尽量让这一点更清楚,$('.travelSwitch').click(function() {}) 所做的是告诉浏览器执行作为参数传递给.click() 的函数,每次点击$('.travelSwitch')。如果$('.travelSwitch').click(function() {}) 被多次调用,浏览器将调用该函数传递的次数与执行此行$('.travelSwitch').click(function() {}) 一样多次,即使您只单击一次。
    • 是的,所以如果点击元素 .travelSwitch function() {} 应该只运行一次。不是两次。我试图弄清楚为什么我没有点击两次开关。
    • 我认为您实际上将要执行的代码与订阅事件混淆了:function () {//ajax} 是您要执行的代码,$(...).click(....) 是告诉浏览器在 click 事件中执行某些操作该选定的元素。因此,如果您告诉浏览器在某个事件中多次执行该操作,每次调用该事件时,它都会执行您要求的多次,就像将许多函数绑定到同一个事件一样,所有这些函数都会一旦事件被调用就触发。在您的情况下,这就像将 2 个函数绑定到点击。
    【解决方案2】:

    好的,我想通了。 正如Wail 所说,我多次使用e.preventDefault(); 来停止事件绑定。 然后因为我通过 javascript 设置了复选框属性,所以我只是用 javascript 更改了它们的值。

    这是我的更新代码:

    $('.travelSwitch').click(function (e) {
            e.preventDefault();
            if ($('.travelSwitch input').attr("checked")) {
                var remTag = false;
                $('.travelSwitch input').attr("checked", false);
            }
            else {
                var remTag = true;
                $('.travelSwitch input').attr("checked", true);
            }
            //send ajax request
            $.ajax({
                method: "POST",
                url: "@Url.Action("ProcessPreferences", "ManagePreferences")",
                data: {
                    //Applies to camping category
                    categoryTag: "Travel",
                    //send user email for processing
                    userEmailAddr: "@userEmailAddr",
                    //send remove flag for processing
                    removeTag: remTag
                }
            })
            .done(function (msg) {
                console.log(msg);
            })
        });
    

    希望这对其他人有帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多