【问题标题】:Ajax Call Custom Model Binder returning FormData in URLAjax 调用自定义模型绑定器在 URL 中返回 FormData
【发布时间】:2015-04-14 17:28:19
【问题描述】:

我为通过 Ajax 发布到的复杂集合创建了自定义模型绑定器。一切都很好,直到我将 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=

【问题讨论】:

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


    【解决方案1】:

    尝试像这样修改您的帖子:

     $.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
        });
    

    【讨论】:

    • 谢谢,我试过了,没有任何变化。 POST 后表单数据仍然返回到 URL。
    • @mflair2000 是你的按钮#SaveButton 一个“按钮”吗?
    • 耶稣。谢谢,原来是这样。我在这里花太多时间在服务器端编码上。
    • 你也可以添加 e.PreventDefault() 来阻止页面跳转提交。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-10-31
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2012-04-24
      相关资源
      最近更新 更多