简体   繁体   English

将javascript对象数组发布到MVC4控制器

[英]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. 现在,当我调试动作时,我有一个IList<SearchParam> ,它已正确初始化为3个元素。 However, fields of each SearchParam object ( Order , Type and Value ) are initialized to null. 但是,每个SearchParam对象( OrderTypeValue )的字段都初始化为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 ;) 但我可能错了;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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