更新
$("#ClassSelect2").append('<option value="' + subcategory.Value + '">' + subcategory.Text + '</option>');
改成
$("#ClassSelect2").append('<option value="' + subcategory + '">' + subcategory + '</option>');
原來不用.Value跟Text就可以了((
如題
我問了GPT後照他的方式改了改可是列表有出來,數量也正確,但文字都是顯示"undefined"
//View
<script type="text/javascript">
$(document).ready(function () {
//監聽第一個下拉選單的 onchange 事件
$("#ClassSelect1").change(function () {
//獲取第一個選單中選擇的選項值
var categoryId = $(this).val();
//使用 AJAX 向服務器發送請求,獲取第二個選單中的選項
$.ajax({
url: '/Home/GetSubcategories', //請求的URL
data: { categoryId: categoryId }, //傳遞的參數
type: 'GET', //請求類型
success: function (subcategories) {
//清空第二個選單
$("#ClassSelect2").empty();
//在第二個選單中顯示選項
$.each(subcategories, function (index, subcategory) {
$("#ClassSelect2").append('<option value="' + subcategory.Value + '">' + subcategory.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve subcategories.' + ex);
}
});
return false;
})
});
</script>
//原先他給我的Controller
[HttpGet]
public ActionResult GetSubcategories(int categoryId)
{
DBmanager db = new DBmanager();
List<class_2> subcategories_G = db.GetClass_2(categoryId);
List<string> subcategories = new();
foreach(var subcategory in subcategories_G)
{
subcategories.Add(subcategory.class_name);
}
return Json(subcategories, JsonRequestBehavior.AllowGet);
}
//後來因為找不到"JsonRequestBehavior.AllowGet"所以改的Controller
[HttpGet]
public ActionResult GetSubcategories(int categoryId)
{
DBmanager db = new DBmanager();
List<class_2> subcategories_G = db.GetClass_2(categoryId);
List<string> subcategories = new();
foreach(var subcategory in subcategories_G)
{
subcategories.Add(subcategory.class_name);
}
return Json(subcategories);
}