Reputation: 31
I'm trying to send data as plain Json, from my controller to the client side of my MVC application. The data is initially collected as a list of objects but I'm having trouble converting it to straight Json. Right now the code in my controller is as follows:
[HttpGet]
public JsonResult SecurityPermissionsTableData()
{
List<SecurityPermissionsGridModel> list = securityPermissionsTable.Get(System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('\\').Last());
string json = JsonConvert.SerializeObject(new
{
data = list
});
return ResultJson(json);
}
public JsonResult ResultJson(object data)
{
return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = data };
}
When I use the JsonConvert.SerializeObject() function, it returns a string:
"{\"data\":[{\"Username\":\"loganfg\",\"readbutton\":null,\"editbutton\":null,\"deletebutton\":null}]}"
However I need to return plain Json in the form of:
{"data":[{"Username":"lgilmore","readbutton":"<a onclick='SP_read(\"7\")' class='SRKbutton tiny SP_rbutton'>Details</a>","editbutton":null,"deletebutton":null}]}
How can I convert the string the serialize function returns to plain Json? Or how do I alter my ResultJson() function to properly handle and convert the string?
Upvotes: 0
Views: 4567
Reputation: 218702
You may simply use the Json
method.
Pass the object you want to convert to json as the parameter.
public JsonResult SecurityPermissionsTableData()
{
var permissionList = securityPermissionsTable
.Get(System.Security.Principal.WindowsIdentity.GetCurrent()
.Name.Split('\\').Last());
return Json(permissionList , JsonRequestBehaviour.AllowGet);
}
Upvotes: 2
Reputation: 887225
JsonResult
already serializes the object for you.
Therefore, it's serializing your string to a JSON string literal.
You should get rid of all of your code and just
return Json(list, JsonRequestBehaviour.AllowGet);
Upvotes: 5