c# - JsonResult 的下拉菜单返回未定义
问题描述
我有两个下拉菜单。一个装有车辆制造商
<select id="vehicleMake" name="VehicleMake">
@foreach (var item in Model.Cars)
{
if (@item.Category == 1072)
{
<option value="@item.UniqueId">@item.Description</option>
}
}
</select>
另一个是空的,应该用车辆模型填充
@Html.DropDownListFor(model => model.VehicleModel, Enumerable.Empty<SelectListItem>(), "Select your model", new {@id="vehicleModel" })
这是我的控制器:
[HttpPost]
public JsonResult GetVehicleModels(string vehicleMake)
{
var vehicleModels = db.Glossaries.Where(x => x.VehicleMakeId.Contains(vehicleMake)).Select(x => x.Description).Distinct().ToList();
SelectList list = new SelectList(vehicleModels);
return Json(new { Success = true, Result = list }, JsonRequestBehavior.AllowGet);
}
这是 AJAX 调用:
<script type="text/javascript">
$("#vehicleMake").on('change', function () {
alert($(this).val());
$.ajax({
type: "POST",
url: "/Registration/GetVehicleModels",
data: JSON.stringify({ 'vehicleMake': $(this).val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
result = $.parseJSON( results );
var toAppend = '';
$.each(result,function(i,o){
toAppend += '<option>' + o.Text + '</option>';
});
$('#vehicleModel').append(toAppend);
},
failure: function (response) {
alert("failure");
},
error: function (response) {
alert("error" + response.responseText);
}
});
});
</script>
这是我在Chrome中的开发人员工具中获得的结果(选择“雪佛兰”时)
Success: true
Result: [{Disabled: false, Group: null, Selected: false, Text: "BROUGHAM", Value: null},…]
0: {Disabled: false, Group: null, Selected: false, Text: "BROUGHAM", Value: null}
Disabled: false
Group: null
Selected: false
Text: "BROUGHAM"
Value: null
下拉列表中填充了“未定义”。我究竟做错了什么?
解决方案
也许这会对某人有所帮助。我在我的应用程序中使用了两个表。一个是我存储从表单中收集的所有信息的地方。另一个(词汇表)包含车辆的品牌和型号。我有两个模型。这就是我最终要做的。
模型词汇表:
public partial class Glossary
{
public int UniqueId { get; set; }
public Nullable<int> Category { get; set; }
public string Description { get; set; } //has both makes and models descriptions
public string VehicleMakeId { get; set; } //has references of Make's UniqueId for Models.
}
这是 MBW 的型号(UniqueId == 3532)在表中的样子
型号注册:
[DisplayName("Vehicle Make")]
public string VehicleMake { get; set; }
[DisplayName("Vehicle Model")]
public string VehicleModel { get; set; }
public List<SelectListItem> Glossary { get; set; } //referencing Glossary model in my view model
注册控制器:
//in public ActionResult Create()
IEnumerable<SelectListItem> CarMake = db.Glossaries.Where(x => x.Category == 1072).Select(x => new SelectListItem
{
Value = x.UniqueId.ToString(),
Text = x.Description
});
ViewBag.VehicleMake = CarMake;
//Json:
[HttpPost]
public JsonResult GetVehicleModels(string VehicleMake)
{
var VehicleModelList = db.Glossaries.Where(m => m.VehicleMakeId == VehicleMake).Select(m => new
{
VehicleModelId = m.UniqueId,
VehicleModelDescription = m.Description
}).ToList();
return Json(VehicleModelList, JsonRequestBehavior.AllowGet);
}
看法:
<div class="form-group">
@Html.LabelFor(model => model.VehicleMake, htmlAttributes: new { @class = "control-label col-md-2 required" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.VehicleMake, (IEnumerable<SelectListItem>)ViewBag.VehicleMake, new { @class = "form-control", required = "required" })
@Html.ValidationMessageFor(model => model.VehicleMake, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.VehicleModel, htmlAttributes: new { @class = "control-label col-md-2 required" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.VehicleModel, Enumerable.Empty<SelectListItem>(), "Select vehicle's make first", new { @id = "VehicleModel", @class = "form-control", required = "required" })
@Html.ValidationMessageFor(model => model.VehicleModel, "", new { @class = "text-danger" })
</div>
</div>
<script type="text/javascript">
$("#VehicleMake").on('change', function () {
$('#VehicleModel option').remove();
$.ajax({
type: "POST",
url: "/Registration/GetVehicleModels",
data: JSON.stringify({ 'vehicleMake': $(this).val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
$.each(result, function (i, o) {
$('#VehicleModel').append('<option value=' + o.VehicleModelId + '>' + o.VehicleModelDescription + '</option>');
});
},
failure: function (response) {
alert("Could not retrieve vehicle model list. ");
},
error: function (response) {
alert("Something's not right... /n" + response.responseText);
}
});
});
</script>
此链接很有帮助:https ://www.aspsnippets.com/Articles/ASPNet-MVC-jQuery-AJAX-and-JSON-Example.aspx
推荐阅读
- html - 使用excel输入查询网站并提取输出
- powershell - 根据内容处置标头跳过在 Powershell 中下载文件
- python - 将分类网络流量特征转换为数值 - ISCX VPN2016 数据集
- c# - 如何在 FFmpeg.AutoGen 中设置 ffmpeg 命令行选项
- javascript - Javascript将数据从一个对象分配给另一个对象会添加重复项
- unity3d - 获取对象在变量中的初始位置并且不改变它的值
- python - 从文件中读取序列作为字符串而不是单个字母python
- vba - 在 MS Access VBA 中使用 IE 对象在类中获取表
- scrollview - SwiftUI:奇怪的行为 ScrollView
- python - python猜随机数游戏不起作用,我的名字没有定义?