【问题标题】:MVC Ajax get with complex type always getting null valuesMVC Ajax 获取复杂类型总是获取空值
【发布时间】:2016-08-18 18:04:26
【问题描述】:

我正在尝试从我的控制器向方法发出 get 请求,但我总是在参数位置内获取空值。

我的模特是:

public class UserLocation
{
    public decimal Lat { get; set; }
    public decimal Long { get; set; }

    public UserLocation() { }
    public UserLocation(decimal lat, decimal lon)
    {
        Lat = lat;
        Long = lon;
    }
}

我的控制器的方法是

    [HttpGet]
    public JsonResult getLocations([FromUri]UserLocation userLocation, int perimeter)
    {
        return Json(LocationsHandler.getLocations(userLocation, perimeter));
    }

还有我的 ajax 调用

function getLocations() {
    var loc = { location: { Lat: "0", Long: "11" } };
    var range = 22;
    $.ajax({
        url: '/Location/getLocations',
        type: 'GET',
        dataType: 'application/json;',
        data: { location: loc, perimeter: range },
        success: function (result) {
            alert(result.Data.length);
            self.Parametros(result.Data);
        },
        error: function (xhr) {
            alert('error');
        }
    });

该方法被调用,并且在第二个参数(周长)中我得到了正确的值,但在我的复杂类型方法中却没有。

有人知道可能是什么问题吗?

【问题讨论】:

  • data: JSON.stringify({ userLocation: { Lat: "0", Long: "11" }, perimeter: range }),(并删除[FromUri]
  • 我尝试了您的解决方案,但问题仍然存在,我尝试将周界添加到 UserLocation 类中,但仍然相同。
  • 刚刚注意到您还有其他问题。您可以简单地将其设为 data: { Lat: 0, Long: 11, perimeter: 22},,但它是一个 GET 方法,因此您还必须指定 return Json(...., JsonRequestBehavior.AllowGet);

标签: ajax asp.net-mvc asp.net-mvc-4


【解决方案1】:

您必须在客户端 Stringify 并在服务器端 反序列化

客户端:

JSON.stringify(loc);

服务器端:

public JsonResult getLocations(JsonObject json, int perimeter)
{
    JavaScriptSerializer js = new JavaScriptSerializer();
    var c = js.Deserialize<MyClass>(json);
}

【讨论】:

    【解决方案2】:

    您可以使用JsonRequestBehaviorAllowGet

    return Json(LocationsHandler.getLocations(userLocation, perimeter),JsonRequestBehavior.AllowGet);
    

    【讨论】:

    • 谢谢我添加了它,但我认为这是为了让 json 返回。
    【解决方案3】:

    检查并判断它是否不起作用。我认为您缺少 contentType 和错误的 dataType。

             $.ajax({
                url: '/Location/getLocations',
                type: 'GET',
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({ location: loc, perimeter: range }),
                success: function (result) {
                    alert(result.Data.length);
                    self.Parametros(result.Data);
                },
                error: function (xhr) {
                    alert('error');
                }
            });
    

    【讨论】:

      猜你喜欢
      • 2018-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-07
      • 1970-01-01
      • 2013-06-30
      相关资源
      最近更新 更多