js動態繫結dropdownList 部分程式碼
(function ($) {
$.fn.Schoolselected = function(settings, extraSettings) {
var options;
options = {
NextSelId: '#Select2',
// SelTextId: '#Showmyselect',
defaultv1: '',
defaultv2: '',
SchoolSelectData: ''
};
return this.each(function() {
$.extend(options, settings, extraSettings);
var _this, _thisnext;
_this = $(this);
_thisnext = $(options.NextSelId);
$.each(options.SchoolSelectData, function(k, v) {
appendOptionTo(_this, v.schoolName, v.Sval, options.defaultv1);
});
_this.change(function() {
_thisnext.html("");
if (this.selectedIndex == -1) return;
var s1_curr_val = this.options[this.selectedIndex].value;
$.each(options.SchoolSelectData, function(k, v) {
if (s1_curr_val == v.Sval) {
if (v.items) {
appendOptionTo(_thisnext, "請選擇", "", options.defaultv2);
$.each(v.items, function(k, v) {
appendOptionTo(_thisnext, v.roomName, v.Rval, options.defaultv2);
});
}
}
});
}).change();
function appendOptionTo($o, k, v, d) {
var $opt = $("<option>").text(k).val(v);
if (v == d) {
$opt.attr("selected", "selected");
}
$opt.appendTo($o);
}
});
};
})(jQuery);
function RfShowMeSchool() {
var scTextID = $.cookie('hahahascSchool');
if (scTextID == undefined) {
return;
}
$("#SchoolId").empty();
$.ajaxSetup({
async: false
});
var MySchoolSelectData;
$.getJSON("/UserCenter/user/GetSchoolSelectList?callback=" + Math.random(), function (data) {
MySchoolSelectData = data;
});
var Schooldefaults = {
NextSelId: '#DormsId',
defaultv1: '',
defaultv2: '',
SchoolSelectData: MySchoolSelectData
};
$('#SchoolId').Schoolselected(Schooldefaults);
}
後臺讀取json資料集:
public string GetSchoolSelectList()
{
var schoolCode = CookieUtil.Get("scSchool").Trim();
var _s = _schoolService.GetSchools(schoolCode);
var _d = _dormsService.GetDorms();
List<Object> alljson = new List<object>();
foreach (var o in _s)
{
List<Object> roommate = new List<object>();
var _dbySchool = _d.Where(a => a.SCHOOLPID.Trim() == o.SCHOOLID);
foreach (var dormSelectModel in _dbySchool)
{
roommate.Add(new
{
roomName = dormSelectModel.Text,
Rval = dormSelectModel.Value
});
}
alljson.Add(new
{
schoolName = o.Text,
Sval = o.Value,
items = roommate
});
}
return JsonConvert.SerializeObject(alljson);
}