我有一个类别下拉列表,我在它的 onchange 事件中编写了以下代码:
function onChange() {
$.ajax(
{
url: '/Home/GetProducts/',
type: 'POST',
data: JSON.stringify({ID:$("#Category").val()}),
//contentType:"application/json; charset=utf-8",
dataType: "json",
success: function (data){
var jsonres = "";
$.each(data, function (i, variant) {
jsonres += '<option value="' + variant.ID + '">' + variant.Name+ '</option>';
});
$("#product").html(jsonres);
}
, error: function () { alert('Error'); }
});
}
我的操作方法是:
[HttpPost]
public ActionResult GetProducts(int? ID)
{
var res = _teacherUow.GetProducts(ID.GetValueOrDefault()).Select(x => new { x.ID, x.Name }).ToList();
return Json(new { Result = true, data = res }, JsonRequestBehavior.AllowGet);
}
我的查看代码:
@Html.DropDownList("Category", new SelectList(ViewBag.Category, "ID", "Name"), new { id = "Category", onchange = "onChange()" })
<select data-val="true" id="product" name="product">
</select>
现在我有三个问题
1-在action方法参数中接收null
json结果是:
{"Result":true,"data":[{"ID":1,"Name":"xxx"},{"ID":3,"Name":"yyyy"}]}
2-但是产品下拉列表成员的值和文本 是“未定义”
3- 使用 html 助手为产品字段创建空下拉列表(用于通过 Ajax 请求填充数据成员) 谁能帮我吗?
最佳答案
问题 1:更改
data: JSON.stringify({ID:$("#Category").val()}),
至
data: { ID: $("#Category").val()},
问题 2:您返回的对象包含 2 个属性 Result
和data
所以成功回调应该是
$.each(data.data, function (i, variant) {
但是您没有使用 Result
属性,无论如何它似乎毫无意义,所以你可以只使用
[HttpGet] // Change this (its a get not a post!)
public ActionResult GetProducts(int? ID) // assume this was a typo
{
var res = _teacherUow.GetProducts(ID.GetValueOrDefault()).Select(x => new { x.ID, x.Name }); // no need to call ToList()
return Json(res, JsonRequestBehavior.AllowGet);
}
并在脚本中使用您的原始代码,除了更改 type: 'POST',
至type: 'GET',
问题 3:创建绑定(bind)到属性 Project
的空下拉列表使用
@Html.DropDownFor(m => m.Project, new SelectList(IEnumerable.Empty<T>))
或分配 IEnumerable.Empty<T>
查看包属性
请注意,我建议对您的脚本进行以下更改
$('#Category').change(function() { // remove the `onChange` attribute in the helper
$('#Project').empty(); // ensure any existing options removed
$.getJSON('@Url.Action("GetProducts", "Home")', { ID: $(this).val() }, function (data) {
$.each(data, function(index, item) {
var option = $('<option></option>').val(item.ID).text(item.Name);
$('#Project').append(option);
});
});
});
关于javascript - 如何将简单的ID(jquery ajax)发布到asp.net mvc中的Action方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26437977/