gpt4 book ai didi

c# - 通过 ajax 将模型发布到 Controller 为空

转载 作者:行者123 更新时间:2023-12-03 20:50:40 24 4
gpt4 key购买 nike

我正在尝试通过 Ajax 将 2 个 ID 发送到 Controller ,如下所示,但该模型根本为空。

我的 View 模型非常简单,如下所示:

public class CityAreaBindingModel
{
public int CityID { get; set; }
public int AreaID { get; set; }
}

View :两个下拉列表,帮助选择城市和地区

        <select class="form-control" id="CityID" name="CityID">
@{
foreach (var city in ViewData["Cities"] as List<SamsungTools.Models.City>)
{
<option value="@city.ID" @(city.ID == 1 ? "selected" : "")>@city.Title</option>
}
}
</select>
<select class="form-control" id="AreaID" name="AreaID">
@{
foreach (var area in ViewData["Areas"] as List<SamsungTools.Models.Area>)
{
<option value="@area.ID" @(area.ID == 1 ? "selected" : "")>@area.Title</option>
}
}
</select>

Ajax:使用 formData 和从 View 中选择的两个 id

var cId = $('#CityID').val();
var aId = $('#AreaID').val();
var data = new FormData();
data.append("CityID", cId);
data.append("AreaID", aId);

$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: 'POST',
url: '/api/GetData/GetSaleCentersByLocation',
data: data,
processData: false,

并且在 Controller 中获取从 ajax 传递的 View 模型:

[HttpPost]
public JsonResult GetSaleCentersByLocation(CityAreaBindingModel model)
{
GeneralStore gs = new GeneralStore();
var saleCentersByCity = gs.GetSaleCentersByCity(model.CityID);
var result = new JsonResult();
result.Data = saleCentersByCity;
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

return result;
}

问题是 Controller 中的模型根本为空。我在 Ajax 中更改了 header 的字段,但以任何其他方式我都会收到错误 415、非法调用、服务器错误 500,...使用上述 Ajax 选项,数据将发送到 Controller ,但模型为空。

有什么解决办法吗?

最佳答案

我认为问题出在 js 代码中的数据结构,请尝试以下代码:

var cId = $('#CityID').val();
var aId = $('#AreaID').val();

var jsonObject = {"CityID": cId , "AreaID": aId };
var data = JSON.stringify(jsonObject);

$.ajax({
'Content-Type': 'application/json'
type: 'POST',
url: '/api/GetData/GetSaleCentersByLocation',
contentType: "application/json",
data: data
success: function (result) {
console.log(result);
}
});

关于c# - 通过 ajax 将模型发布到 Controller 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54839591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com