但DropdownList會因頁面沒有refresh,無法抓取ViewBag的新值。
解決方式可透過getJSON,寫法如下
UI
@Html.DropDownList("NameList", @ViewBag.NameList as IEnumerable)
JavaScript
function loadNames(conditionMd) {
$.getJSON("_NameList", { json: conditionMd }, function (data) {
var selectList = $("#NameList");
selectList.empty();
$.each(data, function (index, optionData) {
var option = $( '').text(optionData.Text).val(optionData.Value);
selectList.append(option);
});
});
}
C#
public ActionResult _NameList(string json)
{
Dictionary< string, string> conditions = new Dictionary< string, string>();
JavaScriptSerializer jss = new JavaScriptSerializer();
conditions = jss.Deserialize< Dictionary< string, string> >(json);
Array result = getNameValues(conditions);
List< SelectListItem> items = new List< SelectListItem>();
items.Add(new SelectListItem { Text = "Plesse select", Value = "Plesse select" });
for (int j = 0; j < result.Length; j++)
{
string[] temp1 = (string[])result.GetValue(j);
items.Add(new SelectListItem { Text = temp1[0], Value = temp1[1] });
}
return Json(items, JsonRequestBehavior.AllowGet);
}
參考資訊How to reload dropdown list values in asp.net mvc3 without refreshing page