MVC中,Ajax Post 数组的实现方案
如果HTML 脚本是这样的话:
<form action="P.aspx" >
<input type="checkbox" name="v" value="v1" />
<input type="checkbox" name="v" value="v2" />
</form>
当Post 的时候, Action 可以是这样:
public User
{
public string[] v {get ;set ;}
}
[HttpPost]
public ActionResult P(User user)
{
...
}
事实上, FORM POST 的时候,POST的数据是: v=v1&v=v2 的样子.
用 Ajax Post 的时候, 由于Post 的是Json 数据, Json 数据的Key 唯一. v只能等于一个值.而如果用数组POST ,如:
$.post("/Account/Register", { "ck": ["c", "k"] }, function (res) {
alert(res);
});
POST数据时,系统会变成:
ck[] : c
ck[] : k
查看 jQuery , 在函数: buildParams处:
function buildParams( prefix, obj ) {
if ( jQuery.isArray(obj) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v );
}
});
} else if ( !traditional && obj != null && typeof obj === "object" ) {
// Serialize object item.
jQuery.each( obj, function( k, v ) {
buildParams( prefix + "[" + k + "]", v );
});
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
我想是这样的:
如果把数组POST 成这要: ck=c&ck=k 那如果ck[0] 还是数组, 事情就会变得很麻烦 . 它会 ck=c&ck=k 有多种意思:
1. ["c","k"]
2. [["c"],["k"]]
3. [["c","k"]]
所以 jQuery 这样写是有道理的.
为了欺骗 type v , 传递的对象可以是这样的
var data = Object();
data[0] = "c" ;
data[1] = "k" ;
//上述写法不是一个数组,而是一个字典, Key 是Int , 让他绑定: prefix + "[" + k + "]" .也可以写为:
var data = Object();
data["0"] = "c" ;
data["1"] = "k" ;
简写为:
$.post("/Account/Register", { ck : {0: "c" , 1 : "k" }}, function (res) {
alert(res);
});
如果要利用第一种方式即 typeof v === "object" || jQuery.isArray(v) 为真, 需要 (C# 表述)
[ (object)"c" , (object)"k" ]
目前,我还没有找到把 js 的 string 转换为 object 的方法. 所以只能用 顺序Int 做字典Key 的方法.
------------------------------------------------------------------------------------------------------------
后记:如果服务器Model 是
public User
{
public string[] names {get;set;}
}
public Dept
{
public User[] users {get ;set ;}
}
Dept作为Model , 客户端该如何提交呢. 这就需要用 ModelBinder 了 . 是否有机制实现从JS 到MODEL 的自动转换, 就不得而知了, 有知道的朋友告知一下.:)