问题描述:

I was wondering if anyone can provide advice here. Using MVC ASP.NET. I have a htmlhelper ddl

 @Html.DropDownListFor(m => m.ddlStartTime, new SelectList(Model.StartTimes, "Text", "Value", ViewBag.selected), new { data_test = "true", @Class = "form-control", onchange = "SubmitDayViewer(this.id)" })

Then I have a AJAX json request which goes and gets my data and returns a partial view along with some other json string data.

 function SubmitDayViewer(pId) {

var obj1 = { dateValue: $('#dteTester').val(), timeValue: $('#ddlStartTime').val(), callerID: pId };

$.ajax({

type: "POST",

url: '@Url.Action("_ADayRoomViewerPartial", "Common")',

data: obj1,

datatype: "json",

success: function (data) {

$("#ddlStartTime").select2("val", data.DDLTimeValue);

}

});

}

The problem I can't overcome is preventing the @Html.DropDownListFor onChange event firing once I change the selected value. So I end up in an infinite loop. I need to devise a way to only fire the event when user changes the actual ddl. manually not when other controls on the page update and as a consequence need to change the selected value dynamically without firing the event. So basically fire onChange on some occasions not all.

网友答案:

remove the change event with off, then re-add it with on:-

function SubmitDayViewer() {
        var obj1 = { dateValue: $('#dteTester').val(), timeValue: $('#ddlStartTime').val(), callerID: this.id};
        $.ajax({
            type: "POST",
            url: '@Url.Action("_ADayRoomViewerPartial", "Common")',
            data: obj1,
            datatype: "json",
            success: function (data) {
                  $("#ddlStartTime").off('change', SubmitDayViewer);
                  $("#ddlStartTime").select2("val", data.DDLTimeValue);
                  $("#ddlStartTime").on('change', SubmitDayViewer);
            }
        });
}

also, use this within the function instead of passing it in.

Edit

If this still happens, then the select2 must be delaying the set somehow. So you could look into the plugin code to see whats going on, or you could add a timeout to re-add the change event.

$("#ddlStartTime").off('change', SubmitDayViewer);
$("#ddlStartTime").select2("val", data.DDLTimeValue);
window.setTimeout(function(){
    $("#ddlStartTime").on('change', SubmitDayViewer);
}, 2000); // 2 seconds

personally I would look in the plugin to find a cleaner solution.

相关阅读:
Top