【问题标题】:Send a javascript object to the server and deserialize using a GET request将 javascript 对象发送到服务器并使用 GET 请求反序列化
【发布时间】:2013-06-20 09:19:29
【问题描述】:

我正在开发一个使用 jquery 和 ajax 进行搜索和更新页面的 MVC4 应用程序。通常要搜索,我会创建一个 javascript 对象并将其发布到我的 ApiController,其中发布参数映射到我的 .NET 搜索输入对象。

我需要将相同的 javascript 搜索对象发送到服务器,但作为 GET 请求,所以我使用 $.param() 来序列化对象。

有没有一种简单的方法可以将查询字符串反序列化为我的 .NET 搜索输入对象?

这是创建的查询字符串的简化版本:

Search[ListId]=41&Search[Query]=test&Search[SortBy]=Location&Search[SortDirection]=Descending&Search[UserTypes][]=2&Search[UserTypes][]=5&Search[UserTypes][]=9&Export[PDF]=false&Export[XLS]=true&Export[XML]=true

这里是我试图反序列化的 SearchInput 对象:

public class SearchInput
{
    public Search Search { get; set; }
    public Export Export { get; set; }
}

public class Search
{
    public int ListId { get; set; }
    public string Query { get; set; }
    public ListViewConfig.SortBy SortBy { get; set; }
    public SortDirection SortDirection { get; set; }
    public List<int> UserTypes { get; set; }
}

public class Export
{
    public bool PDF { get; set; }
    public bool XLS { get; set; }
    public bool XML { get; set; }
}

SortBy 和 SortDirection 是枚举。

【问题讨论】:

    标签: jquery serialization query-string deserialization param


    【解决方案1】:

    好吧,我刚刚解决了自己的问题,但我摆脱了 $.param()

    我使用 json 对我的对象进行编码,对其进行 uri 编码,然后将整个内容作为查询字符串参数发送到我的控制器操作:

    var data = { Search: searchInput, Export: exportInput };
    var url = "/ListViews/Export/";
    var json = encodeURIComponent(JSON.stringify(data));
    var fullUrl = url + "?json=" + json;
    

    然后在我的控制器中,我只需使用 JsonConvert.DeserializeObject 将 json 映射到 .NET 对象:

    var o = JsonConvert.DeserializeObject<ExportObject>(json);
    

    .NET 类:

    public class ExportObject
    {
        public ListViewsApiController.SearchInput Search { get; set; }
        public ExportInput Export { get; set; }
    }
    
    public class ExportInput
    {
        public bool PDF { get; set; }
        public bool XLS { get; set; }
        public bool XML { get; set; }
    }
    
    public class SearchInput
    {
        public int ListId { get; set; }
        public string Query { get; set; }
        public ListViewConfig.SortBy SortBy { get; set; }
        public SortDirection SortDirection { get; set; }
        public List<int> UserTypes { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-15
      • 2016-06-03
      相关资源
      最近更新 更多