【发布时间】:2016-11-22 16:06:38
【问题描述】:
我有一个函数,它使用 AJAX 将下拉列表的值发布到控制器,然后控制器返回取决于所选值的数据。
问题是一直没有返回任何内容,我可以在开发者工具中看到该值被发布为表单数据{"PropertyType":"House"}
当调试PropertyType 时,当控制器被触发但似乎看不出原因时,null 一直是null。
AJAX
function PropertyStyleFilter() {
var propertyType = $('#PropertyType').val();
var Url = '@Url.Action("PropertyStyleFilter")';
//var Url = '/Case/CaseDetails/PropertyStyleFilter/' + PropertyType;
console.log("Property Type:" + PropertyType);
$.ajax({
url: Url,
data: JSON.stringify({ PropertyType: propertyType }),
type: 'POST',
success: function (data) {
$("#PropertyStyle").html(""); // clear before appending new list
$("#PropertyStyle").append($('<option></option>').val("").html("Select Property Style..."));
$.each(data, function (i, style) {
//console.log(i, site);
$("#PropertyStyle").append($('<option></option>').val(style.Value).html(style.Text));
});
if (PropertyType != null) {
$("#PropertyStyle").val(PropertyType);
}
},
error: function (__x, __h, __m) {
console.log('ajax returned error', __m, __x, __h);
}
});
}
控制器
[HttpPost]
public ActionResult PropertyStyleFilter(string PropertyType)
{
var StyleList = (from ps in efContext.PropertyStyles
join pt in efContext.PropertyTypes
on ps.PropertyTypeId equals pt.Id
where pt.TypeName == PropertyType
orderby ps.Id
select new SelectListItem
{
Value = ps.StyleName,
Text = ps.StyleName
});
return Json(StyleList, JsonRequestBehavior.AllowGet);
}
【问题讨论】:
-
在调试javascript时,是否设置了
propertyType?另外,我认为没有必要在您的数据对象周围使用 JSON.stringify(),只需data: { PropertyType: propertyType },即可 -
能否同时添加
dataType: 'json'和contentType: "application/json; charset=utf-8",并重试? -
这是导致问题的 JSON.stringify()...谢谢。
标签: jquery ajax asp.net-mvc