我目前正在关注该教程,以便在asp.net mvc中创建级联下拉列表。
但是,第一个下拉框未加载制造商数据。我假设JSON有错误?我无法弄清楚代码有什么问题。
控制器:
public ActionResult ManufacturerList()
{
var manufacturers = Models.Manufacturer.GetManufacturers();
if (HttpContext.Request.IsAjaxRequest())
{
return Json(new SelectList(manufacturers.ToArray(), "ManCode", "ManName"), JsonRequestBehavior.AllowGet);
}
return RedirectToAction("Index");
}
在模型中:
class Manufacturer
{
public string ManCode { get; set; }
public string ManName { get; set; }
public static IQueryable<Manufacturer> GetManufacturers()
{
return new List<Manufacturer>
{
new Manufacturer {
ManCode = "AC",
ManName = "ACER"
},
}.AsQueryable();
}
}
在视图中:
@using (Html.BeginForm("Index", "Home", FormMethod.Post,
new
{
id = "OrderLaptopFormID"
}))
{
<fieldset>
<legend>Make an order</legend>
<div>
<label for="Manufacturers">Manufacturer</label>
</div>
<select id="ManufacturersID" name="Manufacturers"></select>
</fieldset>
<input type="submit" value="Return" id="SubmitID" />
}
<script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/GetManufacturer.js")"></script>
JS文件:
$(document).ready(function () {
var URL = 'home/ManufacturerList/';
$.getJSON(URL, function (data) {
var items = '<option value="">Select Manufacturer</option>';
$.each(data, function (i, manufacturer) {
items += "<option value='" + manufacturer.Value + "'>" + manufacturer.Text
+ "</option>";
});
$('#ManufacturersID').html(items);
});
});
从这段代码中我会假设应填充制造商下拉列表,但事实并非如此。非常感谢任何人帮助MVC和JSON的新手。谢谢。 感谢你的时间。
更新:所以当我调试时,我收到以下错误: http://localhost:42523/Scripts/countryState.js中第1行第1行的未处理异常 0x800a1391 - JavaScript运行时错误:'$'未定义
答案 0 :(得分:0)
很难说出问题出在哪里,但实际上,Manufacturer
课程没有Value
或Text
属性。相反,它有ManCode
和ManName
。
尝试:
$.each(data, function (i, manufacturer) {
items += "<option value='" + manufacturer.ManCode + "'>" + manufacturer.ManName
+ "</option>";
});
此外,无需返回IQueryable
,只需返回IEnumerable
即可。所以不需要.AsQueryable()
:
public static IEnumerable<Manufacturer> GetManufacturers()
{
return new List<Manufacturer> {
new Manufacturer {
ManCode = "AC",
ManName = "ACER"
}
};
}
最后,不要从方法返回SelectList
,只需返回列表
if (HttpContext.Request.IsAjaxRequest())
{
return Json(manufacturers, JsonRequestBehavior.AllowGet);
}