应用场景:在前端用ajax向服务器提交json对象数组,在controller的以对象数组作为函数的参数,提交的json数组直接转为服务器端的对象数组。
如:
要将json对象数组[{Id:1,Name:"AA"},{Id:2,Name:"BB"}] 用ajax提交,
Controller代码:
public EmptyResult Save(Models.User[] users)
{
return new EmptyResult();
}
方法一:
在前端将json对象用以下方式提交
var url = "http://localhost:8848/User/Save";
var data = {};
data["users[0].Id"] = ;
data["users[0].Name"] = "AA";
data["users[1].Id"] = ;
data["users[1].Name"] = "BB";
$.post(url, data, function () {
alert("提交成功");
});
方法二:
在服务器端自定义ValueProvider
public class JsonArrayValueProviderFactory : ValueProviderFactory
{
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
var formValues = controllerContext.HttpContext.Request.Form; var values = new Dictionary<string, object>();
Regex regex = new Regex(@"\[[A-Za-z]*\]");
for (int i = ; i < formValues.Count; i++)
{
string key = formValues.Keys[i];
var matchs = regex.Matches(key);
if (matchs.Count > )
{
foreach (Match match in matchs)
{
if (match.Value != "[]")
key = key.Replace(match.Value, "." + match.Value.Trim('[', ']'));
}
if (key.EndsWith("[]"))
values.Add(key.Replace("[]", ""), formValues.GetValues(i));
else
values.Add(key, formValues[i]);
}
} return new DictionaryValueProvider<object>(values, System.Globalization.CultureInfo.InvariantCulture);
}
}
添加自定义的ValueProvider,可以再Application_Start执行
ValueProviderFactories.Factories.Add(new JsonArrayValueProviderFactory());
前端:
var url = "http://localhost:8848/User/Save";
var data = { users: [{ Id: 1, Name: "AA" }, { Id: 2, Name: "BB"}] };
$.post(url, data, function () {
alert("提交成功");
});