ajax.beginform onfailure,asp.net mvc - Ajax.BeginForm triggers OnFailure with no reason - Stack Over...

I got stucked with (it seems to be) a simple problem.

My goal is to create a modal with an Ajax form. A child action gets the modal in a partial view, and when edited, submit button posts Ajax form which returns just Json data. Built-in code in Ajax.BeginForm should trigger OnSuccess or OnFailure depending on the result of the action.

The problem is OnFailure is triggered and OnSuccess don't, although the action finishes OK, and post return a 200 code. The "data" param in OnFailure function contains the HTML of the whole page.

This is the code:

(1) Snippet to load the modal in the main view:

(2) Button to open the modal in the main view:

 Modal

(3) The partial view with the modal (and the 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()

}

(4) The Javascript in the main view:

@section scripts

{

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");

}

}

(5) And finally, the controller:

#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

Thanks a lot in advance for your time and help.

Best regards,

Fernando.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值