我有一个JQuery AJAX函数,它获取一个列表,并根据用户对第一个下拉列表的选择填充部分视图下拉列表。
第一个函数触发但不触发第二个函数。第一件是重要的部分。它适用于第一个呼叫,但不适用于第二个呼叫。除了列表名称和部分视图外,两者都是完美的。它不会因任何原因而被解雇。 想法?
脚本
$(document).ready(function () {
$('#SelectedCompanyID').change(function () {
// when the selection of some other drop down changes
// get the new value
var value = $(this).val();
// and send it as AJAX request to the newly created action
$.ajax({
url: '@Url.Action("DivisionDDL")',
type: 'POST',
data: { companyID: value },
success: function (result) {
// when the AJAX succeeds refresh the ddl container with
// the partial HTML returned by the Foo controller action
$('#divisionDDLContainer').html(result);
}
});
});
$('#SelectedDivisionID').change(function () {
// when the selection of some other drop down changes
// get the new value
var value = $(this).val();
// and send it as AJAX request to the newly created action
$.ajax({
url: '@Url.Action("OrgUnitDDL")',
type: 'POST',
data: { divisionID: value },
success: function (result) {
// when the AJAX succeeds refresh the ddl container with
// the partial HTML returned by the Foo controller action
$('#orgUnitDDLContainer').html(result);
}
});
});
});
一些HTML
<tr>
<td><label>Company</label></td>
<td colspan="4">
@Html.DropDownListFor(m => m.SelectedCompanyID, Model.ListCompany)
</td>
</tr>
<tr>
<td><label>Division</label></td>
<td colspan="4">
<div id="divisionDDLContainer">
@Html.Partial("DivisionDDL", Model)
</div>
</td>
</tr>
<tr>
<td><label>Org. Unit</label></td>
<td colspan="4">
<div id="orgUnitDDLContainer">
@Html.Partial("OrgUnitDDL", Model)
</div>
</td>
</tr>
部分观点之一
@model Quest.Models.ViewModelJobDetails
@Html.DropDownListFor(m => m.SelectedDivisionID, Model.ListDivision)
答案 0 :(得分:2)
您将代码设置为绑定到#SelectedDivisionID,当您使用AJAX结果替换divisionDDLContainer div的内容时,此绑定将被销毁:
$('#divisionDDLContainer').html(result);
所以你需要做的就是改变事件绑定的完成方式。
$('#divisionDDLContainer').on('change', '#SelectedDivisionId', function () {
// when the selection of some other drop down changes
// get the new value
var value = $(this).val();
// and send it as AJAX request to the newly created action
$.ajax({
url: '@Url.Action("OrgUnitDDL")',
type: 'POST',
data: { divisionID: value },
success: function (result) {
// when the AJAX succeeds refresh the ddl container with
// the partial HTML returned by the Foo controller action
$('#orgUnitDDLContainer').html(result);
}
});
});
应该给你你想要的东西。这将确保在添加新元素时您的事件会反弹。
如果您选择,请进一步阅读:
答案 1 :(得分:0)
为SelectedDivisionID设置ID 如
@Html.DropDownListFor(m => m.SelectedDivisionID, Model.ListDivision,new {id="SelectedDivisionID"})
也可以使用
$.ajax({
cache:false,//set cache false
type: "POST",
url: '@Url.Action()',
contentType: "application/json; charset=utf-8",//type of data posting to server
data: dataToPost,
dataType:"json",// type of data posted from server
success: function (data) {
}
});