2013-03-08 48 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

相关问题