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

时间:2014-05-02 07:15:24

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

这是我的控制器动作:

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

这是对象模型:

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

以下是我向控制器发送数据的方式:

$.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,
 });

现在,当我调试动作时,我有一个IList<SearchParam>正确初始化为3个元素。但是,每个SearchParam对象(OrderTypeValue)的字段都会初始化为null。这可能是什么问题?

1 个答案:

答案 0 :(得分:2)

我认为,在单个请求中发送数组参数的唯一方法是对其进行字符串化,并在控制器中进行反序列化。

$.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);
}

但我可能错了;)