[英]how to bind the @html.dropdownlist name with id in mvc using JavaScript formate
我需要使用具有名称和id的JavaScript格式在mvc中绑定@ html.dropdownlist。 我尝试但未在JavaScript端进行绑定,但未在客户端传递值。 我的清单值格式图片如下。 如何通过名称和ID而不是序列号传递值。
在您的ajax请求中将类型更改为GET
$.ajax({
type: 'GET',
...
并尝试
$.each(data, function (index, val) {
$('<option/>',{value:val.Id,text:val.Text}).appendTo("#MyDdl");
});
您正在向客户端发送一个SelectList。 此类实现IEnumerable<SelectListItem>
并且SelectListItem具有2个属性: Value
和Text
,您应该将下拉列表绑定到:
$.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);
}
现在,您可以将下拉列表绑定到此集合的Id
和Name
属性:
$.each(data, function () {
$('#MyDdl').append(
$('<option/>', {
value: this.Id,
html: this.Name
})
);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.