Send Model Razor with $ Ajax Serialized to Controller

5

I'm trying to send an object to controller , using ajax .

The object goes to the controller with Json , but only recognizes the values of the get, not the post.

$.ajax({
        type: "POST",
        url: "@Url.Action("AdiconarTeste", "Empresa")",
        data: {empresa:JSON.stringify(@Html.Raw(Json.Encode(Model)))} ,

        success: function (result) {
            if (result.Success != false) {
                if (result.Url != null) {
                    $(location).attr('href', result.Url);
                } else {
                    divLista.html(result);
                    myModal.modal('hide');
                }
            } else {
                alert(result.ErrorMessage);
            }
        }
    });
});

The object arrives like this in the controller:

{
"empresaID":0,
"cidadeID":null,
"objCidade":null,
"nome":null,
"endereco":null,
"bairro":null,
"numero":null,
"cep":null,
"telefone":null,
"fax":null,
"url":null,
"listaTelefones[
    {
    "telefoneID":0,
    "empresaID":null,
    "ObjEmpresa":null,
    "contatoID":null,
    "objContato":null,
    "tipo":3,
    "numero":"69 3226 6565"
    },

Obeservem that the list is populated, this is get of the controller that was done to populate it.

Model:

public class Empresa 
{ 
    public int empresaID { get; set; } 

    [Display(Name = "Cidade")] 
    public int? cidadeID { get; set; } 
    public string fax { get; set; } 
    [Display(Name = "URL"), DataType(DataType.Url, [ErrorMessage = "Url inválida")] 
    public string url { get; set; } 

    public virtual ICollection<Telefone> listaTelefones { get; set; } 
    public virtual ICollection<Teste> listaTestes { get; set; } 
}
    
asked by anonymous 13.06.2014 / 19:01

2 answers

0

You are using JSON.stringify, so in fact you are not sending an object to the server you are sending is a string. Remove the JSON.stringify, so that your data is sent as JSON and not as string:

data: {empresa:@Json.Encode(Model)}
    
19.07.2014 / 16:45
0

Have you tried using this?

@using (Ajax.BeginForm("AdiconarTeste", "Empresa", new AjaxOptions { OnSuccess = "Salvar()", OnComplete = "unlockPage()", OnBegin = "lockPage()", OnFailure = "ajaxHandleError" }, new { @id = "meuForm"}))
{
Coloque os inputs aqui
}
    
18.06.2014 / 18:12