上篇說明透過HttpPost return View()設定DropDownList的內容, 這篇說明透過HttpGet return Json更新部分DropDownList的內容
上篇說明透過HttpPost return View()設定DropDownList的內容, 這篇說明透過HttpGet return Json更新部分DropDownList的內容
STP1. ~/Controllers/HomeController.cs, 在Controller加入兩個HttpGet
public class HomeController : Controller
{
[HttpGet]
public JsonResult getSelectedLine(string selectedCustomer)
{
return Json(getDefaultLine(selectedCustomer, defaultLine), JsonRequestBehavior.AllowGet);
}
[HttpGet]
public JsonResult getSelectedStation(string selectedCustomer, string selectedApplication)
{
return Json(getDefaultStation(selectedCustomer, selectedApplication, defaultStation), JsonRequestBehavior.AllowGet);
}
}
STP2. ~/Views/Home/Index.cshtml, 在View上面加上JQuery
<script>
$(function () {
$('#dlCustomer').change(function () {
getSelectedLine();
getSelectedStation();
});
$('#dlApplication').change(function () {
getSelectedStation();
});
function getSelectedLine() {
var jqCustomer = $('#dlCustomer').val();
var jqPath = '@baseUrl/Home/getSelectedLine/?selectedCustomer=' + jqCustomer;
$.ajax({
url: jqPath,
type: 'Get',
dataType: 'json',
success: function (data) {
$('#dlLine').empty();
$.each(data, function (index, jqOptionData) {
var jqOption = new Option(jqOptionData.Text, jqOptionData.Value, jqOptionData.Selected);
$('#dlLine').append(jqOption);
if (jqOptionData.Selected == true) {
$('#dlLine').val(jqOptionData.Text);
}
});
},
error: function (e) {
alert('getSelectedLine fail! \n' + JSON.stringify(e));
}
});
}
function getSelectedStation() {
var jqCustomer = $('#dlCustomer').val();
var jqApplication = $('#dlApplication').val();
var jqPath = '@baseUrl/Home/getSelectedStation/?selectedCustomer=' + jqCustomer + '&selectedApplication=' + jqApplication
$.ajax({
url: jqPath,
type: 'Get',
dataType: 'json',
success: function (data) {
$('#dlStation').empty();
$.each(data, function (index, jqOptionData) {
var jqOption = new Option(jqOptionData.Text, jqOptionData.Value, jqOptionData.Selected);
$('#dlStation').append(jqOption);
if (jqOptionData.Selected == true) {
$('#dlStation').val(jqOptionData.Text);
}
});
},
error: function (e) {
alert('getSelectedStation fail! \n' + JSON.stringify(e));
}
});
}
});
</script>