How can I get a JsonResult object as a string so I can modify it?

I am using the FlexiGrid jQuery plug in and I need to get a JSON object back form my MVC App, simple enough if the FlexiGrid took just the object but I need to add a few items to the response string for it to work properly with FlexiGrid.

So here is a portion of my controller code:

If Request.QueryString("json") IsNot Nothing Then
    Dim data As New StringBuilder()
    data.Append("page: " & pageIndex & "," & vbCrLf)
    data.Append("total: " & ViewData.TotalCount & "," & vbCrLf)
    data.Append("rows: ")
    data.Append(Json(objCustomerList))

    Return Content(data.ToString())
End If

Unfortunately in the above code Json(objCustomerList) returns 'System.Web.MVV.JsonResult' instead of the desired JSON string data. I also tried Json(objCustomerList).ToString() just to see what would happen and the same thing again.

Any ideas?

Answers


Json() method in ASP.NET MVC is just using the JavaScriptSerializer class via the JsonResult class. You could use that yourself if you wanted to serialize the objCustomerList object using JSON to a string.

My recommendation would be to take a slightly different approach.

  • Create a Model that represented the .NET equivalent of the JavaScript object you were trying to create. Maybe a FlexiGridModel object with Page, Total, Rows, and CustomerList properties.
  • Then when you pass that FlexiGridModel to Json() it would just work, no need to build a JSON string using StringBuilder.

If you just want your code to work there is an override on JavaScriptSerializer.Serialize() that takes the object to serialize and the StringBuilder to append the results to. Which should be exactly what you are looking for.

Some relevant links:


Need Your Help

MySQL ORDER BY Send first to last

mysql sql list order

I managed to properly order my list using this trick, using UNSIGNED variable but the output has a single issue, it places the only entry starting with a letter before the digit entries. (sorting by

How to search Xcode4.2 project?

xcode search xcode4 project xcode4.2

I'd like to run a search on all files in my project. How can this be done in Xcode please?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.