Sending Model to Controller via Ajax

1

I have a strongly typed View with a small form and a javascript function with ajax usage:

function emitir () {
    $.ajax({
        type: "POST",
        traditional: true,
        url: '@Url.Action("EmissaoRapida", "CND")',
        data: { model: @Model },
        success: function (data) {
            alert(data.mensagem);
        },
        error: function () {
            alert("Erro na tentativa de emissão!");
        }
    });
}

I simply want to send my data model to my controller, the method that will receive the model has the following signature:     public JsonResult EmissionRapid (EmissionCND model)

But there is some error, using the Firefox debugger I noticed that something is wrong at the moment of passing the model, because the problem is that the project is not read as I do typing in the view.     @model Pro_Certidoo.Areas.Usuarios.Models.EmissaoCND

In the Pro_Certain error it gets a different color, I believe the problem is there and the message I have is this: JavaScript runtime error: 'Pro_Certain' is not defined

Is there any way to fix this or do something similar by sending the complete data model?

    
asked by anonymous 10.11.2015 / 17:10

2 answers

2

Try to pass the serialized form on the model.

Assuming your form is id formxpto :

function emitir () {
    var model = $("#formxpto").serialize();
    $.ajax({
        type: "POST",
        traditional: true,
        url: '@Url.Action("EmissaoRapida", "CND")',
        data: model,
        success: function (data) {
            alert(data.mensagem);
        },
        error: function () {
            alert("Erro na tentativa de emissão!");
        }
    });
}

Or by jQuery:

$.post("@Url.Action("EmissaoRapida", "CND")", $("#FormFinalizaOrdem").serialize()).done(function (retorno) {}

Your controller should receive the same object from the model, which in this case is Pro_Certidao.Areas.Usuarios.Models.EmissaoCND

If it works, post it to help other people.

EDIT

Your model has to be with the [Serializable] annotation:

using System;

[Serializable]
public class EmissaoCND
{
      //Atributos...
}

Your controller method annotated with [HttpPost] :

[HttpPost]
public ActionResult EmissaoRapida(EmissaoCND EmissaoCND) {}
    
10.11.2015 / 17:21
0

Example below;

function DeleteUser() {
    var dados = { Id: $("#deleteuser").val() };

    $.ajax(
        {
            type: "POST",
            url: "/Usuarios/Delete",
            data: dados,
            success: function (msg) {                       

            },
            error: function () {

            }
        });
}
    
27.11.2015 / 16:05