2013-03-08 91 views
1

我需要使用帶有名稱和ID的JavaScript格式綁定mvc中的@ html.dropdownlist。我嘗試但不綁定在JavaScript方面它不通過客戶端的價值。我的列表值格式圖像如下。如何傳遞名稱和編號而不是序列號的值。如何使用JavaScript formate綁定@ html.dropdownlist名稱與mvc中的id

+0

如何接收JSON樣子? – dakait 2013-03-08 06:06:46

+0

那我該如何實現呢? – 2013-03-08 06:22:40

+0

可以顯示如何在'User'類看起來像 – dakait 2013-03-08 06:25:35

回答

2

類型更改爲您的Ajax請求得到像

$.ajax({ 
type: 'GET', 
... 

,並嘗試

$.each(data, function (index, val) { 
    $('<option/>',{value:val.Id,text:val.Text}).appendTo("#MyDdl"); 
}); 
+0

它不會觸發我的腳本代碼 – 2013-03-08 06:22:21

+0

看到答案更新 – dakait 2013-03-08 07:01:41

+0

已經在它的後期階段 – 2013-03-08 07:13:44

0

你發送的SelectList到客戶端。這個類實現IEnumerable<SelectListItem>和SelectListItem有2個屬性:ValueText,你應該將下降綁定到:

$.ajax({ 
    type: 'POST', 
    url: url, 
    data: { id : id }, 
    success: function (data) { 
     $('#MyDdl').empty(); 
     $.each(data, function() { 
      $('#MyDdl').append(
       $('<option/>', { 
        value: this.Value, 
        html: this.Text 
       }) 
      ); 
     }); 
    } 
}); 

在您的例子,你用val.Id但有沒有這樣的屬性。

但事實上你不需要任何SelectList。剛剛回歸的學生集合:

[HttpPost] 
public ActionResult Some(string id) 
{ 
    var students = service.GetAllStudents().ToList(); 
    students.Insert(0, new StudentModel{ Id = 0, Name = "Select student" }); 
    return Json(students); 
} 

,現在您可以在下拉列表綁定到這個集合的IdName屬性:

$.each(data, function() { 
    $('#MyDdl').append(
     $('<option/>', { 
      value: this.Id, 
      html: this.Name 
     }) 
    ); 
}); 
+0

海達林,我期待你。我的問題是我的json沒有重新運行到客戶端。它在我的客戶端沒有觸發 – 2013-03-08 06:59:14

+0

你的意思是'成功'回調沒有被激怒?你的控制器操作是否被調用您的JavaScript控制檯中是否存在一些錯誤?你能看到在FireBug中發送的AJAX請求嗎?你在哪裏調用'$ .ajax'方法?它是在點擊或提交處理程序?如果是這樣,您是否通過從此處理程序返回false來取消默認操作,以防止瀏覽器重定向? 「StudentModel」實體JSON是可序列化的(即它的對象圖中不包含任何循環引用)?許多問題將幫助您找到問題。 – 2013-03-08 06:59:55

相關問題