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

标签 c# asp.net ajax model-view-controller

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

我的 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/

相关文章:

c# - 总计 Gridview 上的列并显示在页脚中

javascript - 虽然我改变了标签的文本它仍然返回初始值,我该如何解决?

javascript - 从字符串中解析 HTML

c# - 如何在模型类中将 appsettings.json 文本作为 SQL 连接字符串传递? (具体例子)

c# - 形状上的均匀分布算法

c# - protobuf-net 如何实现可观的性能?

c# - 错误 : Invalid postback or callback argument

c# - 双线性插值 - DirectX 与 GDI+

asp.net - 亚马逊 MWS - 计算的请求签名与提供的签名不匹配

node.js - 如何在响应 AJAX 请求之前等待 Express 中的异步响应?