Ajax调用自定义模型Binder返回URL中的FormData

时间:2015-04-14 17:28:19

标签: jquery ajax model-view-controller model-binding

我已经为我通过Ajax发布的复杂集合创建了一个自定义Model Binder。一切都很好,直到我将JsonResult返回到页面,然后将整个FormData附加到URL。我在这里缺少什么小事?

我有一些ajax发布表单。

  $(document).ready(function() {
   $("#SaveButton").click(function(e) {
    var form = $("#myForm");
    $.ajax({
        type: "POST",
        url: '/myController/SaveAll',
        data: form.serialize(),
        dataType: "json",
        error: function(xhr) {
            console.log('Error: ' + xhr.statusText);
        },
        success: function(result) {
            console.log(result);
        },
        async: true
    });
});

});

控制器动作。

      public JsonResult SaveAll([ModelBinder(typeof(CustomModelBinder))]ProvinceListViewModel model)
    {
           // process something
            return this.Json(new
            {
                Sucess = true
            }, JsonRequestBehavior.AllowGet);

    }

这是我使用request.FormData

的自定义模型绑定器
 public class CustomModelBinder : DefaultModelBinder
{
    private NameValueCollection _formCollection;

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType == typeof(ProvinceViewModel))
            {
                HttpRequestBase request = controllerContext.HttpContext.Request;

                // set the form collection 
                this._formCollection = request.Form;


                // build the view models, parse form collection


                // return the tab container view model
                return new ProvinceViewModel();



            }
            else
            {
                return base.BindModel(controllerContext, bindingContext);
            }
        }
 }

结果url附加了表单数据。我该如何防止这种情况?提前致谢。         _RequestVerificationToken = PK4YYR1fTh15rpHQwE883NlVOLho7LLWL7cdH_3jP0lq8SXhKGvOHq7imuBUf-xr6sOP5dIMbVMPVcPuA1Rsgt616x3Tub4DK57VCGZ4-OO1&安培; MYID =

2 个答案:

答案 0 :(得分:0)

尝试修改你的帖子:

 $.ajax({
        type: "POST",
        url: '/myController/SaveAll',
        data: {'Data':form.serialize()},
        dataType: "json",
        error: function(xhr) {
            console.log('Error: ' + xhr.statusText);
        },
        success: function(result) {
            console.log(result);
        },
        async: true
    });

答案 1 :(得分:0)

问题是我在表单中有一个提交按钮,并附加了onclick事件。我将其更改为div元素,问题得到解决。