Outputting Json with the Razor view engine

心已入冬 提交于 2020-01-22 18:51:14

问题


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.


回答1:


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.




回答2:


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




回答3:


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();
        }
    }
}


来源:https://stackoverflow.com/questions/4367062/outputting-json-with-the-razor-view-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!