Jorge
Jorge

Reputation: 18237

Can't serialize an object

I defined a model like this

public class Planilla
{
    [Key]
    public int IDPlanilla { get; set; }

    [Required(ErrorMessage = "*")]
    [Display(Name = "Dirección de Negocio")]
    public int IDDireccionDeNegocio { get; set; }

    [Required (ErrorMessage = "*")]
    public string Nombre { get; set; }
    [Display(Name = "Descripción")]
    public string Descripcion { get; set; }

    public bool Activo { get; set; }

    [ScriptIgnore]
    public virtual DireccionDeNegocio DireccionDeNegocio { get; set; }
}

And I have a method in my controller that returns the first element of this model

    [HttpPost]
    public ActionResult GetElements(string IDCampana)
    {
        Planilla query = db.Planillas.First();
        return Json(query);                 
    }

My problem is when I invoke this method from client side throws an error that say's

circular reference is detected trying to serialize System.Data.Entity.DynamicProxies.Planilla_7F7D4D6D9AD7AEDCC59865F32D5D02B4023989FC7178D7698895D2CA59F26FEE Debugging my code I realized that the object returned by the execution of the methodFirstit's a {System.Data.Entity.DynamicProxies.Planilla_7F7D4D6D9AD7AEDCC59865F32D5D02B4023989FC7178D7698895D2CA59F26FEE} instead a Model of my namespace like Example.Models.DireccionDeNegocio`.

Why am I doing wrong?? Because I tried with other models and work's well

Upvotes: 0

Views: 211

Answers (2)

jrummell
jrummell

Reputation: 43077

System.Data.Entity.DynamicProxies.* is the Entity Framework proxy namespace. Your DbContext creates your entities as such to support lazy loading and change tracking. This isn't your problem. The problem likely lies in a circular association.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

Use view models, that's the only advice I can give you. Never pass domain models to your views. It's as simple as that. And if you respect this simple rule and fundamental rule in ASP.NET MVC applications you will never have problems. So for example if you need only the id and the description in your view:

[HttpPost]
public ActionResult GetElements(string IDCampana)
{
    Planilla query = db.Planillas.First();
    return Json(new 
    { 
        Id = query.IDPlanilla, 
        Description = query.Description 
    });
}

Notice that in this case the anonymous object serves as view model. But if you really wanted to do things properly you would write your view model:

public class PlanillaViewModel
{
    public int Id { get; set; }
    public string Description { get; set; }
}

and then:

[HttpPost]
public ActionResult GetElements(string IDCampana)
{
    Planilla query = db.Planillas.First();
    return Json(new PlanillaViewModel 
    { 
        Id = query.IDPlanilla, 
        Description = query.Description 
    });
}

By the way Ayende wrote a nice series of blog posts about this.

Upvotes: 3

Related Questions