今日在用MVC練習製作連動式下拉選單,但一直遇到一個問題,在控制器回傳資訊給前端的jquery時,下拉選單的text一直會呈現全白或者是[Object object]的情況,欲詢問這該怎麼解才好@_@ ,謝謝大家!
text出現以下狀況,但value在檢查中是有拿到值的,同時選單項目數量也是正確的,唯一問題就是text無法顯示出我要的值。
示意圖
全空白
[Object object]
VIEW
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
Customer @Html.DropDownList("CustomerList", (IEnumerable<SelectListItem>)ViewBag.items ,"--請選擇--", new { @class="form-control" , id="Customer"})
</p>
<p>
Order <select name="orders" id="Orders" class="form-control"><option>----</option></select>
</p>
<script type="text/javascript" language="javascript">
<!--
$(document).ready(function () {
$('#Customer').change(function () { ChangeCustomer(); });
})
function ChangeCustomer() {
var SelectedCustomer = $('#Customer option:selected').val();
if ($.trim(SelectedCustomer).length > 0) {
GetOrders(SelectedCustomer);
}
}
function GetOrders(customerID) {
$.ajax({
url: '@Url.Action("Orders","Home")',
data: { customerID: customerID },
type: 'post',
cache: false,
async: false,
datatype: 'json',
success: function (data) {
if (data.length > 0) {
$('#Orders').empty();
$('#Orders').append($('<option></option>').val('').text('--請選擇訂單--'));
$.each(data, function (i, item) {
//$('#Orders').append($('<option></option>').val(i).text.get(item));
$('#Orders').append($('<option>', {
value: i,
text: item
}));
})
}
}
})
}
</script>
CONTROLLER
using DropDownListProject.Models;
using DropDownListProject.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace DropDownListProject.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
HomeModel A = new HomeModel();
List<CustomerViewModel> mRet = new List<CustomerViewModel>();
mRet = A.GetCustomerList();
SelectList items = new SelectList(mRet,"CUSTOMERID","CUSTOMERNAME");
ViewBag.items = items;
return View();
}
[HttpPost]
public JsonResult Orders(string customerID)
{
HomeModel A = new HomeModel();
List<KeyValuePair<string, string>> items = new List<KeyValuePair<string, string>>();
//若customerID不為空且有值,則從資料庫取資料出來
if (!string.IsNullOrWhiteSpace(customerID))
{
var mRet = A.GetOrderList(customerID);
if (mRet.Count() > 0)
{
foreach (var order in mRet)
{
items.Add(new KeyValuePair<string, string>(order.OrderID, string.Format("{0}",order.OrderDate)));
}
}
}
return this.Json(items);
}
}
}