【问题标题】:Ajax.BeginForm triggers OnFailure with no reasonAjax.BeginForm 无故触发 OnFailure
【发布时间】:2020-07-13 10:08:57
【问题描述】:

我遇到了(似乎是)一个简单的问题。

我的目标是创建一个带有 Ajax 表单的模式。子操作在局部视图中获取模式,并且在编辑时,提交按钮发布仅返回 Json 数据的 Ajax 表单。 Ajax.BeginForm 中的内置代码应根据操作的结果触发 OnSuccess 或 OnFailure。

问题是 OnFailure 被触发,而 OnSuccess 没有被触发,尽管操作完成正常,并且发布返回 200 代码。 OnFailure 函数中的“data”参数包含整个页面的 HTML。

这是代码:

(1) 在主视图中加载模态的片段:

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
     @Html.Action("GetDialogV2", "Fianzas", new { idArrendamiento = Model.Id_Arrendamiento })
</div>

(2) 主视图中打开modal的按钮:

<button type="button" class="btn btn-outline-primary" data-toggle="modal" data-target="#exampleModal">
      <i class="far fa-hand-holding-usd"></i>&nbsp;Modal
</button>

(3) 带有模态(和Ajax Form)的局部视图,GetDialogV2.cshtml:

@model EditFianzas_vm

@{
    AjaxOptions ajaxOptions = new AjaxOptions
    {
        HttpMethod = "POST",
        UpdateTargetId = "Respuesta",
        OnSuccess = "OnSuccess",
        OnFailure = "OnFailure"
    };
}

@using (Ajax.BeginForm(ajaxOptions))
{
    @Html.AntiForgeryToken()

    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Fianza</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="form-horizontal">
                    @Html.ValidationSummary(true)
                    @Html.HiddenFor(model => model.Id_Arrendamiento)

                    <div class="form-group">
                        @Html.LabelFor(model => model.Importe, new { @class = "control-label col-md-6" })
                        <div class="col-md-8">
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text"><i class="far fa-euro-sign"></i></span>
                                </div>
                                @Html.EditorFor(model => model.Importe, new { htmlAttributes = new { @class = "form-control importe" } })
                            </div>
                            @Html.ValidationMessageFor(model => model.Importe, "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.Fecha_Abono, new { @class = "control-label col-md-6" })
                        <div class="col-md-8">
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text"><i class="far fa-calendar"></i></span>
                                </div>
                                @Html.TextBoxFor(model => model.Fecha_Abono, "{0:dd/MM/yyyy}", new { @class = "form-control datepicker" })
                            </div>
                            @Html.ValidationMessageFor(model => model.Fecha_Abono, "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-md-8">
                            <input type="text" id="Respuesta" class="form-control" />
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer justify-content-between">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
                <button type="submit" class="btn btn-primary" id="botonPrueba">Guardar</button>
            </div>
        </div>
        <!-- /.modal-content -->
    </div>
}

(4) 主视图中的Javascript:

@section scripts
{
    <script type="text/javascript">
        function OnSuccess(data) {
            if (data.Success == true) {
                toastr.success("Operación realizada.", "Fianzas");
                $("#exampleModal").modal('hide');
            }
            else {
                if (data.modelState) {
                    $.each(d.modelState, function (i, item) {
                        toastr.info(i + ': ' + item, "i: item");
                        //item.valid(); //run jQuery validation to display error
                        $('#' + i).valid();
                    });
                }
                else {
                    toastr.error(data.Error, "Fianzas");
                }
            }
        }

        function OnFailure(data) {
            alert(data);
            alert('HTTP Status Code: ' + data.param1 + '  Error Message: ' + data.param2);
            toastr.error("Se ha producido un error no controlado al realizar la operación.", "Fianzas");
            toastr.warning(data, "Fianzas");
        }
    </script>
}

(5) 最后是控制器:

#region Ajax Form (GetDialogV2)
public PartialViewResult GetDialogV2(int idArrendamiento)
{
    //Obtengo el modelo...
    Arrendamientos_Fianzas fianza = db.Arrendamientos_Fianzas.Find(idArrendamiento);
    //Creo la vista-modelo...
    EditFianzas_vm vm = new EditFianzas_vm {
        Id_Arrendamiento = idArrendamiento,
        Importe = fianza.Importe,
        Fecha_Abono = fianza.Fecha_Abono
    };

    return PartialView(vm);
}

[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult GetDialogV2(EditFianzas_vm vm)
{
    try
    {
        if (!ModelState.IsValid)
        {
            var modelState = ModelState.ToDictionary
            (
                kvp => kvp.Key,
                kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
            );
            modelState.Add("hdId_Arrendamiento", modelState["vm.Id_Arrendamiento"]);
            modelState.Remove("vm.Id_Arrendamiento");
            modelState.Add("txtImporte", modelState["vm.Importe"]);
            modelState.Remove("vm.Importe");
            modelState.Add("txtFecha_Abono", modelState["vm.Fecha_Abono"]);
            modelState.Remove("vm.Fecha_Abono");
            return Json(new { modelState }, JsonRequestBehavior.AllowGet);
            //throw (new Exception("Error en la validación del modelo."));
        }
        //Miro a ver si existen datos para este arrendamiento (no sé si es un edit o un new, si quiero hacerlo todo en una misma acción)
        Arrendamientos_Fianzas fianza = db.Arrendamientos_Fianzas.Find(vm.Id_Arrendamiento);
        //Compruebo si es nuevo o editado...
        if (fianza == null)
        {
            //Nuevo registro...
            fianza = new Arrendamientos_Fianzas
            {
                Id_Arrendamiento = vm.Id_Arrendamiento,
                Importe = vm.Importe,
                Fecha_Abono = vm.Fecha_Abono
            };
            //Actualizo info de control...
            fianza.C_Fecha = DateTime.Now;
            fianza.C_IdUsuario = Usuario.NombreUsuario;
            fianza.C_Comentarios = "Alta de la fianza.";
            //Guardo registro...
            db.Arrendamientos_Fianzas.Add(fianza);
        }
        else
        {
            //Estoy editando, grabo valores...
            fianza.Importe = vm.Importe;
            fianza.Fecha_Abono = vm.Fecha_Abono;
            //Actualizo info de control...
            fianza.C_Fecha = DateTime.Now;
            fianza.C_IdUsuario = Usuario.NombreUsuario;
            fianza.C_Comentarios = "Modificación de los datos de la fianza.";
            //Modifico estado del registro en el modelo...
            db.Entry(fianza).State = EntityState.Modified;
        }
        //Guardo cambios...
        db.SaveChanges();
        //Return...
        return new JsonResult() { Data = Json(new { Success = true }) };
    }
    catch (Exception ex)
    {
        return new JsonResult() { Data = Json(new { Success = false, Error = ex.Message }) };
    }
}
#endregion

非常感谢您的宝贵时间和帮助。

最好的问候, 费尔南多。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-5.2 ajax.beginform


    【解决方案1】:

    我明白了。这是一个微妙的解决方案,我几乎没有猜到:

    如果禁用了 Javascript,或者在某些情况下,您需要显式地将操作传递给 AjaxOptions,如下所示:

        AjaxOptions ajaxOptions = new AjaxOptions()
        {
            HttpMethod = "POST",
            OnSuccess = "OnSuccess(data)",
            OnFailure = "OnFailure",
            OnBegin = "OnBegin",
            OnComplete = "OnComplete",
            Url = Url.Action("GetDialogV2")
        };
    

    【讨论】:

      猜你喜欢
      • 2018-08-03
      • 2018-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-23
      • 2014-12-09
      • 2020-04-27
      • 2012-09-17
      相关资源
      最近更新 更多