MVC中用ajax提交json对象数组

应用场景:在前端用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"] = 1;
data["users[0].Name"] = "AA";
data["users[1].Id"] = 2;
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 = 0; i < formValues.Count; i++)
        {
            string key = formValues.Keys[i];
            var matchs = regex.Matches(key);
            if (matchs.Count > 0)
            {
                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);
    }
}
View Code

添加自定义的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("提交成功");
});

posted @ 2013-10-19 17:15  zengyy  阅读(3104)  评论(1编辑  收藏  举报