在GET请求中绑定复杂对象的数组-jquery.praram()传统标志

Bind array of complex objects in GET request - jquery.param() traditional flag

本文关键字:praram -jquery 标志 传统 数组 请求 GET 绑定 对象 复杂      更新时间:2023-09-26

我正在尝试对以下控制器操作进行jquery.ajax调用:

public ActionResult Handler(SemanticPart[] semanticParts, string first, string last)

我有以下数据JSON对象和具有公共{get;set;}属性的相应服务器端模型:

 var data = {
      semanticParts: [{ hasLabel: "label", hasType: "type", hasIndex : 0 }],
      first: "first",
      last : "last"                             
 };

问题是jQuery.param似乎没有针对默认MVC模型绑定器的序列化选项。

decodeURIComponent($.param(data))产生:

 "semanticParts[0][hasLabel]=label&semanticParts[0][hasType]=type&semanticParts[0][hasIndex]=0&first=first&last=last"

同时设置traditional标志,使decodeURIComponent($.param(data, true))产生:

 "semanticParts=[object+Object]&first=first&last=last"

MVC用于复杂数组的默认模型绑定器需要以下内容才能正确绑定(在Fiddler Composer中测试):

 "semanticParts[0].hasLabel=label&semanticParts[0].hasType=type&semanticParts[0].hasIndex=0&first=first&last=last"

哪个简单地使用:array[0].property=而不是array[0][property]=

我知道所有的web框架都没有对参数字符串达成一致的通用规范,但我无法理解为什么传统标志设置为true的jQuery.param会返回[object+object]……这在任何框架中都是毫无用处的。

有办法解决这个问题吗?

也许是用正则表达式将模式[#][text]替换为[#].text?(实际上,这个的编码版本更相关)

您应该实现一个模型来保存以下参数:

public class SemanticPartViewModel 
{
  public List<SemanticPart> semanticParts { get; set;} 
  public string first { get; set; }
  public string last { get; set;}
}

并更改控制器以将其作为参数接收

public ActionResult Handler(SemanticPartViewModel semanticParts)
{
  /*Do stuff*/
}

您还应该使用JSON.stringfy(mydata)为$.ajax调用创建数据

通过这种方式,默认的modelbinder将处理其余部分。