简体   繁体   中英

Posting javascript array of objects to MVC4 controller

This is my controller action:

public ActionResult BrowsePartial(IList<SearchParam> searchParams = null)
{
   //...
}

This is the object model:

public class SearchParam
{
    public string Order { get; set; }
    public string Type { get; set; }
    public string Value { get; set; }
}

And here is how i send data to controller:

$.ajax(
{
   type: "GET",
    url: url,
    data: { searchParams: [{ Order: "fghfdhgfdgfd", Type: "sasdsa", Value: "saddsadsads" }, { Order: "fghfdhgfdgfd", Type: "sasdsa", Value: "saddsadsads" }, { Order: "fghfdhgfdgfd", Type: "sasdsa", Value: "saddsadsads" }] },
    mode: "replace",
    cache: false,
 });

Now, when i debug the action, i have an IList<SearchParam> that is correctly initialized with 3 elements. However, fields of each SearchParam object ( Order , Type and Value ) are initialized to null. What could be the problem here?

I think, the only way you can send your array parameter in a single request is to stringify it, and deserialize in your controller.

$.ajax(
{
   type: "GET",
    url: url,
    data: { searchParams: JSON.stringify([{ Order: "fghfdhgfdgfd", Type: "sasdsa", Value: "saddsadsads" }, { Order: "fghfdhgfdgfd", Type: "sasdsa", Value: "saddsadsads" }, { Order: "fghfdhgfdgfd", Type: "sasdsa", Value: "saddsadsads" }])},
    mode: "replace",
    cache: false,
 });


public ActionResult BrowsePartial(string searchParams = null)
{
    SearchParam params = JsonConvert.DeserializeObject<SearchParam>(searchParams);
}

But I maybe mistaken ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM