0

Guys, I'm havin a problem with this...

My User class has a property UserType userType like below:

    public class User
{
    public virtual int  Id { get; set; }
    public virtual string User { get; set; }
    public virtual string Name { get; set; }
    public virtual UserType userType { get; set; }
}

I can't return a JSON, like this...

[HttpGet]
    public JsonResult JSONUsers(string q)
    {
        IEnumerable<User> model = dataServ.Users.GetUsers( q );
        return this.Json( new { Result = model }, JsonRequestBehavior.AllowGet );
    }

I'm getting an error:

A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'.

The reason I'm getting this error is the Lazy-Load (at least that's what I understood), and to poorly solve it, I did:

public JsonResult JSON(string q)
    {
        List<User> model = new List<User>();
        IEnumerable<User> users= dataServ.Users.Getusers( q );

        foreach (var item in users)
        {
            User user = new User
            {
                Id = item.Id,
                Name = item.Name
            };
            model.Add( user );
        };

        return this.Json( new { Result = model }, JsonRequestBehavior.AllowGet );
    }

I don't think this is a good solution. In this case I only need de "Id" and "Name" properties, but what if I need all properties? Will I have to copy one by one? Can Anybody tell me if there is a better solution?

Thanks,

Thiago

1 Answer 1

3

Ayende wrote a great series of blog posts about this problem.

But to summarize: USE VIEW MODELS => and by the way that's the solution to more than half of the questions on StackOverflow about ASP.NET MVC that I am answering.

2
  • Ok, I can use a view model, but then I'll have 2 similar classes. Is this a really good option? Tks for sharing your knowledge.
    – Thiago
    Commented May 16, 2011 at 19:05
  • @Thiago Guttierre, you won't have the circular reference between them. So, yes they will be similar (that's where AutoMapper comes in handy) and are considered best practice when working with ASP.NET MVC. Commented May 16, 2011 at 19:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.