0

Below is my MVC View model

public class UserViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int UserID { get; set; }
    public IEnumerable<Role> LstRole { get; set; }
}

I need to convert this to JSON in controller action method which emits JSON to angularjs function

Below is my action method in controller

public string GetAllUsers()
{
    objUserView.LstRole = objUserManager.GetAllRoles();
    objUserView.FirstName = "Test";
    objUserView.LastName = "Test 1";
    objUserView.UserID = 1;
    return JsonConvert.SerializeObject(objUserView.LstRole, Formatting.None, new JsonSerializerSettings()
    {
        NullValueHandling = NullValueHandling.Ignore,
        TypeNameHandling = TypeNameHandling.All
    });
}

When I run this action method it gives below error

Self referencing loop detected for property 'Role' with type 'System.Data.Entity.DynamicProxies.Role_EE4037A57E80F8AE5D8E070E7325B72D7AE3916C26C19F53CB6F5084B2181234'. Path '$valuesenter code here[1].UserMasters.$values[0]'.

Please assist

Grewal
  • 1
  • Whats the `Role` model? –  Jan 23 '15 at 09:40
  • In jsonSerializesettings did you try : 'ReferenceLoopHandling = ReferenceLoopHandling.Serialize' OR 'PreserveReferencesHandling = PreserveReferencesHandling.Objects' – Dakshal Raijada Jan 23 '15 at 09:43
  • possible duplicate of [JSON.NET Error Self referencing loop detected for type](http://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop-detected-for-type) –  Jan 23 '15 at 09:47
  • You should probably make a RoleViewModel as well, since that is (most likely) referencing a list of Users, which in turn is referencing Role. Also, returning a list of users attached to a role may be a potential security risk. – Patrick Jan 23 '15 at 10:16

2 Answers2

1

Add this ReferenceLoopHandling = ReferenceLoopHandling.Ignore to JsonSerializerSettings

like below

public string GetAllUsers()
{
    objUserView.LstRole = objUserManager.GetAllRoles();
    objUserView.FirstName = "Test";
    objUserView.LastName = "Test 1";
    objUserView.UserID = 1;
    return JsonConvert.SerializeObject(objUserView.LstRole, Formatting.None, new JsonSerializerSettings()
    {
        NullValueHandling = NullValueHandling.Ignore,
        TypeNameHandling = TypeNameHandling.All,
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
    });

}

sylwester
  • 16,498
  • 1
  • 25
  • 33
0

Did you try converting it on the view? Something like that may help: Convert view model data to json

Community
  • 1
  • 1
Burak Karakuş
  • 1,368
  • 5
  • 20
  • 43