Question

I'm working on an MVC4 app using jquery & ajax to do searches and update the page. Normally to search I create a javascript object and post it to my ApiController where the post parameters are mapped to my .NET search input object.

I need to send the same javascript search object to the server, but as a GET request, so I'm using $.param() to serialise the object.

Is there an easy way to deserialize the querystring to my .NET search input object?

Here is a simplified version of the querystring that is created:

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

Ands here is the SearchInput object I'm trying to deserialize to:

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 are enums.

Was it helpful?

Solution

Well I just solved my own problem, but I got rid of $.param()

I encode my object with json, uri encode it, and send the whole thing to my controller action as a querystring parameter:

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

Then in my controller, I simply use JsonConvert.DeserializeObject to map the json to a .NET object:

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

.NET Classes:

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; }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top