如何在asp.net mvc中向Action方法发布简单ID(jquery-ajax)

how to post simple ID (jquery ajax) to Action method in asp.net mvc

本文关键字:jquery-ajax 布简单 简单 ID 方法 asp net mvc Action 中向      更新时间:2023-09-26

我有一个类别下拉列表,我在它的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:您返回的对象包含两个属性Resultdata,因此成功回调应该是

$.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);
    });
  });
});