Enviar datos desde javascript hacia un controller con AJAX en MVC
Método #1: Enviar form como JSON y otros parametros
Llamado Ajax
var f = $("#form_refin").serializeFormJSON();
var send = { param1: "111", param2: "222", datos: JSON.stringify(f) };
jqxhr2 = $.ajax({
type: "POST",
data: send,
dataType: "json",
url: "@Url.Action("Supervision2", "RefinanciacionArrendamiento")",
beforeSend: function () {
//l.start();
}
}).fail(function (jqXHR, textStatus) {
//l.stop();
alert("Error: " + "Status: " + jqXHR.status + " detalle: " + textStatus + " detalle: " + jqXHR.responseText);
}).success(function (data) {
$("#HashSup").val(data);
});
(function ($) {
$.fn.serializeFormJSON = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
Controller
using Newtonsoft.Json;
...
...
...
[HttpPost]
public ActionResult Supervision2(string param1, string param2, string datos)
{
var refin = JsonConvert.DeserializeObject<RefinanciacionArrendamientoVM>(datos);
Método #2: Definir el objeto que se va a enviar manualmente
Llamado Ajax
$("#Modificar").click(function() {
var user = {
Documento: $("#txtDocumento").val(),
Email: $("#txtCorreo").val(),
Nombre: $("#txtNombre").val(),
TipoDoc: $("#drpTipoDoc option:selected").val()
}
jqxhr2 = $.ajax({
type: "POST",
async: false,
data: user,
dataType: "json",
url: "@Url.Action("ModificarUsuarioCreado", "Usuario")",
beforeSend: function () {}
})
.fail(function (jqXHR, textStatus) {})
.success(function (data) {}
);
});
Controller
[HttpPost]
public ActionResult ModificarUsuarioCreado(Usuario user) { ... }
public class Usuario
{
public string Documento { get; set; }
public string Email { get; set; }
public string Nombre { get; set; }
public string TipoDoc { get; set; }
}
Método #3: Enviar el Modelo completo
Controller
Método #4: Enviar el form serializado
De esta forma se pasan todos los datos del formulario (no del modelo, aunque si no se modifican los campos del form, son los mismos)
Este método permite pasar los cambios que se hagan en el formulario (cosa que el método #2 no puede hacer)
Llamado Ajax
jqxhr2 = $.ajax({
}).fail(function (jqXHR, textStatus) {
if (data.MsgError == "Refinanciación contabilizada correctamente.") {
type: "GET",
data: $('form').serialize(),
dataType: "json",
url: "@Url.Action("Contabilizar", "RefinanciacionArrendamiento")",
beforeSend: function () {
$.blockUI({
message: 'Espere por favor...',
css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
opacity: 0.5,
color: '#fff'
}
});
}
$.unblockUI();
$("#arrendContent").html(jqXHR.responseText);
}).success(function (data) {
$.unblockUI();
$("#div_mensaje").html(data.MsgError);
$("#btn_contabilizar").attr("disabled", "disabled");
$("#btn_calcular").attr("disabled", "disabled");
}
});
Llamado Ajax
var f = $("#form_refin").serializeFormJSON();
var send = { param1: "111", param2: "222", datos: JSON.stringify(f) };
jqxhr2 = $.ajax({
type: "POST",
data: send,
dataType: "json",
url: "@Url.Action("Supervision2", "RefinanciacionArrendamiento")",
beforeSend: function () {
//l.start();
}
}).fail(function (jqXHR, textStatus) {
//l.stop();
alert("Error: " + "Status: " + jqXHR.status + " detalle: " + textStatus + " detalle: " + jqXHR.responseText);
}).success(function (data) {
$("#HashSup").val(data);
});
(function ($) {
$.fn.serializeFormJSON = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
Controller
using Newtonsoft.Json;
...
...
...
[HttpPost]
public ActionResult Supervision2(string param1, string param2, string datos)
{
var refin = JsonConvert.DeserializeObject<RefinanciacionArrendamientoVM>(datos);
}
Método #2: Definir el objeto que se va a enviar manualmente
Llamado Ajax
$("#Modificar").click(function() {
var user = {
Documento: $("#txtDocumento").val(),
Email: $("#txtCorreo").val(),
Nombre: $("#txtNombre").val(),
TipoDoc: $("#drpTipoDoc option:selected").val()
}
jqxhr2 = $.ajax({
type: "POST",
async: false,
data: user,
dataType: "json",
url: "@Url.Action("ModificarUsuarioCreado", "Usuario")",
beforeSend: function () {}
})
.fail(function (jqXHR, textStatus) {})
.success(function (data) {}
);
});
Controller
[HttpPost]
public ActionResult ModificarUsuarioCreado(Usuario user) { ... }
public class Usuario
{
public string Documento { get; set; }
public string Email { get; set; }
public string Nombre { get; set; }
public string TipoDoc { get; set; }
}
Método #3: Enviar el Modelo completo
De esta forma se puede enviar el modelo desde la vista hacia un controller, cualquiera sea su estructura y complejidad.
Funciona con POST y GET, en este ejemplo se utiliza POST.
*** Tener en cuenta que utilizando este método NO se envían los datos modificados manualmente en el formulario o los datos cargados mediante javascript. Para poder hacer esto, utilizar el método 3 ***
Código en la View
Formulario:
@using Creditos.ViewModels.Liquidaciones
@model RefinanciacionArrendamientoVM
...
...
...
Llamado Ajax
var model = JSON.parse('@Html.Raw(Json.Encode(Model))');
jqxhr2 = $.ajax({
type: "POST",
data: model,
dataType: "json",
url: "@Url.Action("Contabilizar", "RefinanciacionArrendamiento")"
}).fail(function (jqXHR, textStatus) {
$("#arrendContent").html(jqXHR.responseText);
}).success(function (data) {
$("#div_mensaje").html(data.MsgError);
});
jqxhr2 = $.ajax({
type: "POST",
data: model,
dataType: "json",
url: "@Url.Action("Contabilizar", "RefinanciacionArrendamiento")"
}).fail(function (jqXHR, textStatus) {
$("#arrendContent").html(jqXHR.responseText);
}).success(function (data) {
$("#div_mensaje").html(data.MsgError);
});
[HttpPost]
public ActionResult Contabilizar(RefinanciacionArrendamientoVM refin)
...
...
...
public ActionResult Contabilizar(RefinanciacionArrendamientoVM refin)
...
...
...
De esta forma se pasan todos los datos del formulario (no del modelo, aunque si no se modifican los campos del form, son los mismos)
Este método permite pasar los cambios que se hagan en el formulario (cosa que el método #2 no puede hacer)
Llamado Ajax
jqxhr2 = $.ajax({
}).fail(function (jqXHR, textStatus) {
if (data.MsgError == "Refinanciación contabilizada correctamente.") {
type: "GET",
data: $('form').serialize(),
dataType: "json",
url: "@Url.Action("Contabilizar", "RefinanciacionArrendamiento")",
beforeSend: function () {
$.blockUI({
message: 'Espere por favor...',
css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
opacity: 0.5,
color: '#fff'
}
});
}
$.unblockUI();
$("#arrendContent").html(jqXHR.responseText);
}).success(function (data) {
$.unblockUI();
$("#div_mensaje").html(data.MsgError);
$("#btn_contabilizar").attr("disabled", "disabled");
$("#btn_calcular").attr("disabled", "disabled");
}
});
Cuando se actualizan los datos del modelo en el controller los cambios no se reflejan en la vista
Problema:
Cuando en un action de un controller se modifican datos del modelo y se hace el return View, en la vista no aparecen actualizados dichos datos.
Solución:
Es necesario hacer ModelState.Remove("nombre-del-atributo")
Por ejemplo:
public ActionResult Prueba(ElModelo m)
{
m.Nombre = "el nuevo nombre";
ModelState.Remove("Nombre");
}
Suscribirse a:
Comentarios (Atom)