Send Model Razor with $Ajax Serialized Controller

Asked

Viewed 1,450 times

5

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

The object goes to the controller with Json, but recognizes only the values of get, not 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 this way 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"
    },

Note that the list is populated, this is get from the controller that was performed 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; } 
}
  • 1

    How’s your Controller code?

  • 1

    You have put [Httppost] above the Controller statement?

  • public class Enterprise { public int empresaID { get; set; } [Display(Name = "City")] public int? cidadeID { get; set; } public string fax { get; set; } [Display(Name = "URL"), Datatype(Datatype.Url, [Errormessage = "Invalid url")] public string url { get; set; } public virtual Icollection<Phone> listTelefones { get; set; } public virtual Icollection<Test> listTestes { get; set; } }

2 answers

0

Have you tried that?

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

0


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

data: {empresa:@Json.Encode(Model)}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.