通过ajax发布到控制器的模型为空

Meh*_*hdi 2 c# asp.net ajax model-view-controller

我正尝试通过Ajax仅向控制器发送2个ID,如下所示,但是该模型完全为空。

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

public class CityAreaBindingModel
{
    public int CityID { get; set; }
    public int AreaID { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

查看:两个下拉列表,可帮助选择城市和区域

        <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>
Run Code Online (Sandbox Code Playgroud)

Ajax:将formData与视图中的两个选定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,
Run Code Online (Sandbox Code Playgroud)

在控制器中,只是从ajax传递视图模型:

[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;
}
Run Code Online (Sandbox Code Playgroud)

问题在于控制器中的模型完全为空。我在Ajax中更改了标头的字段,但是以任何其他方式,我将收到错误415,非法调用,服务器错误500,...使用上述Ajax选项,数据将发送到控制器,但模型为null。

有什么办法吗?

Ham*_*asi 5

我认为问题出在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);
    }
});
Run Code Online (Sandbox Code Playgroud)