Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outputting Json with the Razor view engine

I've got a dictionary<string,string> as part of my view model. What I'm trying to do is cycle this object and output it as a json object. My reason for this is so I can localise my client script files correctly.

The output for this needs to look something like

var clientStrings = {"test":"yay","goodBye":"Nah"};

Any ideas how to achieve this correctly.

Thanks in advance.

like image 332
RubbleFord Avatar asked Dec 06 '10 13:12

RubbleFord


3 Answers

It's built into MVC. Just return Json(yourobject).

like image 106
Matt Sherman Avatar answered Oct 16 '22 21:10

Matt Sherman


Considering you are on mvc 3 you'll have access to JavaScriptSerializer. You should be able to do the following:

JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize((object)yourDictionary);

This will serialize your dictionary to json. You may want to do this in the controller before sending the ViewData to the view to render.

like image 10
Jeremy B. Avatar answered Oct 16 '22 21:10

Jeremy B.


Also you can integrate the free Json.NET library within your code.

This library does not suffer the problems JavascriptSerializer has like the circular reference problem.

This is a sample using the library to output JSON from a controller action

public virtual ActionResult ListData() {
    Dictionary<string, string> openWith = new Dictionary<string, string>();
    openWith.Add( "txt", "notepad.exe" );
    openWith.Add( "bmp", "paint.exe" );
    openWith.Add( "dib", "paint.exe" );
    openWith.Add( "rtf", "wordpad.exe" );

    JsonNetResult jsonNetResult = new JsonNetResult();
    jsonNetResult.Formatting = Formatting.Indented;
    jsonNetResult.Data = openWith;
    return jsonNetResult;
}

If you execute this action you will get the following results

{
  "txt": "notepad.exe",
  "bmp": "paint.exe",
  "dib": "paint.exe",
  "rtf": "wordpad.exe"
}

JsonNetResult is a simple custom wrapper class around the functionalities of the Json.NET library.

public class JsonNetResult : ActionResult
{
    public Encoding ContentEncoding { get; set; }
    public string ContentType { get; set; }
    public object Data { get; set; }

    public JsonSerializerSettings SerializerSettings { get; set; }
    public Formatting Formatting { get; set; }

    public JsonNetResult() {
        SerializerSettings = new JsonSerializerSettings();
    }

    public override void ExecuteResult( ControllerContext context ) {
        if ( context == null )
            throw new ArgumentNullException( "context" );

        HttpResponseBase response = context.HttpContext.Response;

        response.ContentType = !string.IsNullOrEmpty( ContentType )
            ? ContentType
            : "application/json";

        if ( ContentEncoding != null )
            response.ContentEncoding = ContentEncoding;

        if ( Data != null ) {
            JsonTextWriter writer = new JsonTextWriter( response.Output ) { Formatting = Formatting };

            JsonSerializer serializer = JsonSerializer.Create( SerializerSettings );
            serializer.Serialize( writer, Data );

            writer.Flush();
        }
    }
}
like image 8
Lorenzo Avatar answered Oct 16 '22 22:10

Lorenzo