从 JsonResult 下拉返回 undefined [英] Dropdown from JsonResult returns undefined
问题描述
我有两个下拉菜单.一个是车辆制造商
另一个是空的,应该填充车辆模型
@Html.DropDownListFor(model => model.VehicleModel, Enumerable.Empty(), "选择你的模型", new {@id="vehicleModel" })
这是我的控制器:
[HttpPost]公共 JsonResult GetVehicleModels(字符串车辆制造){var VehicleModels = db.Glossaries.Where(x => x.VehicleMakeId.Contains(vehicleMake)).Select(x => x.Description).Distinct().ToList();SelectList list = new SelectList(vehicleModels);返回 Json(new { Success = true, Result = list }, JsonRequestBehavior.AllowGet);}
这是 AJAX 调用:
这是我在 Chrome 的开发者工具中得到的结果(选择雪佛兰"时)
成功:true结果:[{Disabled: false, Group: null, Selected: false, Text: "BROUGHAM", Value: null},...]0:{禁用:假,组:空,选定:假,文本:BROUGHAM",值:空}禁用:假组:空已选择:假文字:布鲁姆"值:空
下拉列表中填充了未定义".我做错了什么?
也许这会对某人有所帮助.我在我的应用程序中使用了两个表.一个是我存储从表单收集的所有信息的地方.另一个(词汇表)包含车辆的品牌和型号.我有两个模型.这是我最终做的事情.
模型词汇表:
公共部分类词汇表{公共 int UniqueId { 获取;放;}public Nullable类别{得到;放;}公共字符串 描述 { get;放;}//有品牌和型号说明公共字符串 VehicleMakeId { 获取;放;}//有对模型的 Make 的 UniqueId 的引用.}
这是Makes在表格中的样子
这是表中 MBW 模型(UniqueId == 3532)的样子
模型注册:
[DisplayName("Vehicle Make")]公共字符串 VehicleMake { 获取;放;}[DisplayName("车辆型号")]公共字符串 VehicleModel { 获取;放;}公共列表词汇表 { 得到;放;}//在我的视图模型中引用词汇表模型
注册控制器:
//在公共ActionResult Create()IEnumerableCarMake = db.Glossaries.Where(x => x.Category == 1072).Select(x => new SelectListItem{值 = x.UniqueId.ToString(),文本 = x.描述});ViewBag.VehicleMake = CarMake;//杰森:[HttpPost]公共 JsonResult GetVehicleModels(string VehicleMake){var VehicleModelList = db.Glossaries.Where(m => m.VehicleMakeId == VehicleMake).Select(m => new{VehicleModelId = m.UniqueId,VehicleModelDescription = m.Description}).ToList();返回 Json(VehicleModelList, JsonRequestBehavior.AllowGet);}
查看:
@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)ViewBag.VehicleMake, new { @class = "form-control", required = "required" })@Html.ValidationMessageFor(model => model.VehicleMake, "", new { @class = "text-danger" })
<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
<script type="text/javascript">$("#VehicleMake").on('change', function () {$('#VehicleModel 选项').remove();$.ajax({类型:POST",url: "/Registration/GetVehicleModels",数据:JSON.stringify({ 'vehicleMake': $(this).val() }),contentType: "application/json; charset=utf-8",数据类型:json",成功:功能(结果){$.each(result, function (i, o) {$('#VehicleModel').append('<option value=' + o.VehicleModelId + '>' + o.VehicleModelDescription + '</option>');});},失败:功能(响应){alert("无法检索车辆型号列表.");},错误:函数(响应){alert("有些不对劲.../n" + response.responseText);}});});
此链接很有帮助:https://www.aspsnippets.com/Articles/ASPNet-MVC-jQuery-AJAX-and-JSON-Example.aspx
I have two dropdowns. One is populated with vehicle makes
<select id="vehicleMake" name="VehicleMake">
@foreach (var item in Model.Cars)
{
if (@item.Category == 1072)
{
<option value="@item.UniqueId">@item.Description</option>
}
}
</select>
The other one is empty and should be populated with vehicle models
@Html.DropDownListFor(model => model.VehicleModel, Enumerable.Empty<SelectListItem>(), "Select your model", new {@id="vehicleModel" })
This is my controller:
[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);
}
This is the AJAX call:
<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>
This is the results I'm getting in Developer Tools in Chrome (when 'Chevrolet' is chosen)
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
The dropdown is populated with 'undefined'. What am I doing wrong?
Maybe this will help somebody. I am using two tables in my application. One is where I'm storing all the info I'm collecting from the form. The other one (Glossary) holds makes and models of vehicles. I have Models for both. Here is what I ended up doing.
Model Glossary:
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.
}
This is what Makes look like in the table
This is what Models of MBW (UniqueId == 3532) look like in the table
Model Registration:
[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
Registration Controller :
//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);
}
View:
<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>
This link was helpful: https://www.aspsnippets.com/Articles/ASPNet-MVC-jQuery-AJAX-and-JSON-Example.aspx
这篇关于从 JsonResult 下拉返回 undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!