【问题标题】:Json ModelBinding not working from Ajax in MVC3 RC2 [closed]Json ModelBinding 在 MVC3 RC2 中无法从 Ajax 工作 [关闭]
【发布时间】:2011-01-08 19:29:46
【问题描述】:

我正在尝试在 MVC3 RC2 中将 Ajax 与 JSON 模型绑定一起使用,但由于某种原因,数据没有通过控制器操作方法。关于这个主题还有其他帖子,但有些是指较旧版本的 MVC,而我发现的这些帖子都没有到位。由于我是 JSON 和 JSON ModelBinding 的新手,并且在 jQuery Ajax 调用方面没有那么丰富的经验,所以我很容易错过一些东西。

我的出发点是 Scott Guthrie 的帖子 http://bit.ly/btdFP5Javascript 和 AJAX 改进 部分中介绍了 MVC3 预览,但我正在从 Google API 中提取地图数据,因此我的代码略有不同:

        var bounds = map.getBounds();
        var southWest = bounds.getSouthWest();
        var northEast = bounds.getNorthEast();

        var mb = { nelat: northEast.lat(), nelng: northEast.lng(), swlat: southWest.lat(), swlng: southWest.lng() };

        $.ajax(
            {
                url: "/home/GetMarkers",
                type: "post",
                dataType: "json",
                data:JSON.stringify(mb),
                contentTYpe: "application/json; charset=utf-8",
                success: function (result) {
                ...

success 函数一切正常,所以我已经停止了那里的代码列表。

我在项目的域模型中有一个用于纬度/经度坐标的类:

Public Class MapBounds
    Public Property nelat As Double
    Public Property nelng As Double
    Public Property swlat As Double
    Public Property swlng As Double
End Class

控制器动作是:

Function GetMarkers(ByVal mb As MapBounds) As JsonResult
    Dim objMarkers = ... get relevant data from database
    Return Json(objMarkers)
End Function

通过 Firebug 观察到的发布的 JSON 数据(通常)是:

{"nelat":51.22959997248028,"nelng":9.811035156249996,
"swlat":42.190280664203,"swlng":-7.8110351562500036}

但返回 MapBounds 对象中属性的值全为零。我已经尝试过传递参数的各种变体,包括传递单个值,但没有运气。这些值要么为零,要么为空。

Phil Haack 的帖子 - http://bit.ly/bUl21b - 在将 JSON 发送到操作方法参数时说 JsonValueProviderFactory 现在是 MVC3 的一部分,但我还是检查了它是否存在(它是)。

【问题讨论】:

    标签: asp.net-mvc json jquery asp.net-mvc-3


    【解决方案1】:

    您的 contentType 参数中有错字,这可能会导致无法正确设置。应该是contentType 而不是contentTYpe

    【讨论】:

    • 在那里阅读doh时刻。只是表明你的大脑看到了它期望看到的东西。谢谢。
    • 有一个campaign to clean up Stack Overflow 删除这些与错字相关的问题 - 我们真的可以使用你的帮助!你介意在这个问题上投下密切的一票吗?
    • 抱歉,我不认为这些是题外话,不会投票结束。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多