首页 > 技术文章 > MVC从视图传参到Controller几种方式

qiuyan 2014-07-11 00:42 原文

简单数组传递

var array = ["aaa", "bbb", "ccc"];
 $.ajax({
       url:"@Url.Action("Test")",
       type: "POST",
       data: { array: array },
       traditional: true //需要写上该属性,Controller才能接收到
 });

 public ActionResult Test(List<string> array) {
            return null;
   }

单个模型传递

@using (Html.BeginForm("Test", "Home")) {
    <p><input type="text" name="No" value="001"/></p>
    <p><input type="text" name="Name" value="Tom" /></p>
    <p><input type="text" name="Age" value="24"/></p>
    <p><input type="checkbox" name="Courses" value="语文" />
        <input type="checkbox" name="Courses" value="数学" />
        <input type="checkbox" name="Courses" value="外语" />
    </p>
    <p><button type="submit">提交</button></p>
}
public ActionResult Test(Student student) {
            return null;
        }

多个模型传递

1.方式一

 var models = [];
                models.push({ No: "001", Name: "Tom", Age: 20, Courses: ["语文", "数学", "外语"] });
                models.push({ No: "002", Name: "Jeff", Age: 21, Courses: ["语文", "数学", "外语"] });
                models.push({ No: "003", Name: "Hacks", Age: 22, Courses: ["语文", "数学", "外语"] });
                $.ajax({
                    url: '@Url.Action("Test")',
                    data: JSON.stringify(models),//第一个地方,需要进行JSON序列化
                    type: 'POST',
                    contentType: 'application/json',//第二个地方,需要声明为'application/json',默认'application/x-www-form-urlencoded'
                    success: function (data) {

                    }
                });

public ActionResult Test(List<Student> models) {
            return null;
  }

2.方式二 (Model Binder)

需要借助ModelBinder来处理,添加一个类 :JsonModelBinderAttribute.cs

 public class JsonModelBinderAttribute : CustomModelBinderAttribute {
        public override IModelBinder GetBinder() {
            return new JsonBinder();
        }
    }
    public class JsonBinder : IModelBinder {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
            //return base.BindModel(controllerContext, bindingContext);
            if (controllerContext == null) {
                throw new ArgumentNullException("controllerContext");
            }

            if (bindingContext == null) {
                throw new ArgumentNullException("bindingContext");
            }

            var prefix = bindingContext.ModelName;
            string jsonString = controllerContext.RequestContext.HttpContext.Request.Params[prefix];
            if (jsonString != null) {
                var serializer = new JavaScriptSerializer();
                var result = serializer.Deserialize(jsonString, bindingContext.ModelType);
                return result;

            }
            else {
                return null;
            }


        }
    }
  var models = [];
                models.push({ No: "001", Name: "Tom", Age: 20, Courses: ["语文", "数学", "外语"] });
                models.push({ No: "002", Name: "Jeff", Age: 21, Courses: ["语文", "数学", "外语"] });
                models.push({ No: "003", Name: "Hacks", Age: 22, Courses: ["语文", "数学", "外语"] });
                $.ajax({
                    url: '@Url.Action("Test")',
                    data: { models: JSON.stringify(models) },
                    type: 'POST',
                    success: function (data) {

                    }
                });

public ActionResult Test([JsonModelBinder]List<Student> models) {
            return null;
        }

参考:http://ishwor.cyberbudsonline.com/2012/07/fun-with-aspnet-mvc-3-custom-json-model-binder.html

推荐阅读