我的应用程序中有一个 ViewModel,如下所示:
public class ItemViewModel {
public string Name { get; set; }
public string SelectedType { get; set; }
public IEnumerable<Type> Types { get; set; }
public string SelectedSubtype { get; set; }
public IEnumerable<Subtype> Subtypes { get; set; }
}
我创建了一个视图来公开这些属性:
@Html.TextBoxFor(m => m.Name)
@Html.DropDownListFor(m => m.SelectedType,
new SelectList(Model.Types, "ID", "Description"),
"Select a type")
@Html.DropDownListFor(m => m.SelectedSubtype,
new SelectList(Model.Subtypes, "ID", "Description"),
"Select a subtype")
好吧,当我想刷新我的子类型下拉列表时,我必须编写大量 DOM 代码来生成新选项。
$('#SelectedType').change(function() {
$.get('/json/GetSubtypesFromType', { 'type': $(this).val() }, function(result) {
var options = '';
for (var count = 0; count < result.length; count++) {
options += "<option value='" + result[count].ID + "'>" + result[count].Description + "</option>";
}
$('#SelectedSubtype').html(options);
});
});
有没有办法将新选项绑定到可枚举的子类型,ViewModel
而不是编写此代码以生成选项。我需要在发布表单时检索新的可枚举,但我想将新值绑定到ViewModel
集合中。