如何在asp.net mvc中向Action方法发布简单ID(jquery-ajax)
how to post simple ID (jquery ajax) to Action method in asp.net mvc
我有一个类别下拉列表,我在它的onchange事件中编写了blow代码:
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-在动作方法参数中接收空
json结果是:
{"Result":true,"data":[{"ID":1,"Name":"xxx"},{"ID":3,"Name":"yyyy"}]}
2-但是产品下拉列表成员的值和文本是"未定义"
3-使用html助手为product字段创建空下拉列表(用于Ajax请求填充数据成员)有人能帮我吗?
问题1:更改
data: JSON.stringify({ID:$("#Category").val()}),
至
data: { ID: $("#Category").val()},
问题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:要创建绑定到属性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);
});
});
});
相关文章:
- 另一个ajax调用中的Jquery ajax调用在for循环中没有按预期工作
- 将curl查询转换为jQuery.ajax()
- jQuery AJAX write to XML
- jQuery Ajax GET请求工作不正常
- jquery ajax https调用给出ERR_INSECURE_RESPONSE
- 简单的jQuery AJAX JSON调用
- 使用 jquery/ajax 制作一个简单的 RSS 提要
- Jquery Ajax 简单应用程序:缺少 ) 参数列表之后
- jQuery/Ajax简单聊天机器人,如何忽略小写字母
- 如何在asp.net mvc中向Action方法发布简单ID(jquery-ajax)
- 如何使用简单的jquery ajax调用上传文件
- 简单的Jquery/Ajax加载不起作用
- 一个简单的jQuery/AJAX查询
- 简单的Jquery Ajax从Mysql建议
- 请求获得最简单的jquery-ajax教程
- 编写一个简单的jQuery AJAX请求
- 使用jquery ajax的Laravel简单crud
- 从php到jquery/ajax中获得回显或返回字符串的最简单方法是什么?
- Jquery ajax简单表单不工作
- 简单的jQuery AJAX泄漏在FF4 (Windows7)