2

In My ASPMVC Code I filled the ViewBag.Contacts variable by use the below code

        var contactsGroups = EntityContext.DBContext.TS_GetConfirmedContacts(typeId,AccountId).GroupBy(c=>c.GroupName);
       // JSONGroup Custom object  
       List<JSONGroup> jsonContactsGroups = new List<JSONGroup>();
        foreach (var group in contactsGroups)
        {
            jsonContactsGroups.Add(new JSONGroup
            {
                GroupName = group.Key,
                Objects = new List<object>(group.ToList())
            });
        }


        var result = new JsonResult
        {
            Data = jsonContactsGroups,
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };

        ViewBag.Contacts =  result;

When I am tried to access the ViewBag.Contacts variable from javascript by this Code

var contactData = '@ViewBag.Contacts';

After debugging the value returned as string [from console]

var contactData = 'System.Web.Mvc.JsonResult';

3 Answers 3

4

You can not use JsonResult to return a Json formated string. JsonResult class is inherited from ActionResult class, so the returned value is an object containing Json formated 'Data' property and some other properties for response. so and using @ symbol to output the result , will return the name of class as string. if you want to serialize an object to a Json object , use Newtonsoft's Json.NET serializer or use the .NET build in JavaScriptSerializer class.

Newtonsoft :

String serializedResult = JsonConvert.SerializeObject(jsonContactsGroups);

JavaScriptSerializer :

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer() ;
String serializedResult = serializer.Serialize(result);

Then return the Json serialized string to the view :

ViewBag.Contacts =  serializedResult;

But if you want to return a Json model or result to the view , i suggest you to write your action method as JsonResult method.

Sign up to request clarification or add additional context in comments.

1 Comment

Using NewtonSoft worked for me, though I had to prepend JsonConvert with Newtonsoft.Json as in Newtonsoft.Json.JsonConvert.SerializeObject().
2

Use Html.Raw and Json.Encode like

var model = @Html.Raw(Json.Encode(ViewBag.Contacts));

// fetch data

$.each(model.Data, function() {
    console.log($(this).attr("GroupName"));
});

Comments

0

Use JSON.Net(it may already be referenced since MVC uses it as default serializer)

using Newtonsoft.Json;

ViewBag.Contacts = JsonConvert.SerializeObject(jsonContactsGroups, Formatting.Indented);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.