我有以下表格:
@model ProductFilterModel
<form action="@Url.Action("Search","ProductSearch", new{@Model})" method="get" class="vehicle-filter group">
<div class="select">
@Html.DropDownListFor(x=>x.VehicleYearId,new List<SelectListItem>
{
new SelectListItem{ Text="2016", Value="2016"},
new SelectListItem{ Text="2015", Value="2015"},
},new{@class="year"})
</div>
<div class="select">
<select id="MakeDropDownList" name="VehicleMakeId" class="make" disabled data-request-url="@Url.Action("GetVehicleMakes","ProductFilter")"></select>
</div>
</form>
当VehicleYearId
下拉列表更改时,我会去获取Vehicle Makes,但不会在JSON
参数中返回data
,而是返回整个HTML文档。这是年度变化时我正在运行的javascript:
$('#VehicleYearId').on('change', function() {
$.ajax({
url: $makeDropDownList.attr('data-request-url'),
method: 'GET',
dataType: 'json',
data: { year: $yearDropDownList.find(':selected').val() },
success: function (data) {
$('#MakeDropDownList').empty();
$('#MakeDropDownList').append($('<option/>', { value: "-1", text: "MAKE" }));
$('#MakeDropDownList').find('option[value="-1"]').prop('disabled', true);
$('#MakeDropDownList').find('option[value="-1"]').prop('selected', true);
$(data).each(function (index, item) {
$('#MakeDropDownList').append($('<option/>', { value: item.Id, text: item.Name }));
});
$('#MakeDropDownList').prop('disabled', false);
}
});
});
它抛出错误说出意外的令牌<
,原因是它返回的是整个html文档,而不仅仅是所选选项的选择值。如果我在ajax调用之外使用$yearDropDownList.find(':selected').val()
,它将返回选定的年份。以下是返回车辆的方法,基本上是make下拉列表的data-request-url
:
public JsonResult GetVehicleMakes(string year)
{
var vehicleMakes = _vehicleRepository.GetVehicleMakes(year);
return Json(vehicleMakes, JsonRequestBehavior.AllowGet);
}
当我检查ajax调用中的错误参数时,这就是我所拥有的:
jqXHR - Object {readyState: 4, responseText: "
↵<!doctype html>
↵<html>
↵<head>
↵
↵ <title>SC…</div><!--module-->
↵
↵</footer>
↵
↵
↵</html>", status: 200, statusText: "OK"}
textStatus - parseerror
errorThrown - SyntaxError: Unexpected token <(…)
这是控制器:
public class ProductFilterController : Controller
{
readonly VehicleRepository _vehicleRepository = new VehicleRepository();
public JsonResult GetVehicleMakes(string year)
{
var vehicleMakes = _vehicleRepository.GetVehicleMakes(year);
return Json(vehicleMakes, JsonRequestBehavior.AllowGet);
}
public JsonResult GetVehicleModels(string make)
{
var vehicleModels = _vehicleRepository.GetVehicleModels(make);
return Json(vehicleModels, JsonRequestBehavior.AllowGet);
}
public JsonResult GetVehicleYears()
{
var vehicleYears = _vehicleRepository.GetVehicleYears();
return Json(vehicleYears, JsonRequestBehavior.AllowGet);
}
public JsonResult GetVehicleEngines(string model)
{
var vehicleEngines = _vehicleRepository.GetVehicleEngines(model);
return Json(vehicleEngines, JsonRequestBehavior.AllowGet);
}
}