locked
Save JSON data as file. RRS feed

  • Question

  • User-352524747 posted

    I use a simple code with json.write() method to display json data in the browser.

    Is it possible to directly download as a json file, if the user request the page?

    Saturday, June 13, 2015 5:17 PM

Answers

  • User-821857111 posted

    Yes. You need to set the Response's content type to application/octet-stream and the content disposition to attachment:

    @{
        var cars = new List<Car>{
            new Car{Make = "Ford", Model = "Fiesta", Colour = "Red"},
            new Car{Make = "Ford", Model = "Fiesta", Colour = "Green"},
            new Car{Make = "Ford", Model = "Fiesta", Colour = "Black"},
            new Car{Make = "Ford", Model = "Fiesta", Colour = "Blue"},
            new Car{Make = "Ford", Model = "Fiesta", Colour = "White"}
        };
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment; filename=cars.json");
    }
    @Html.Raw(Json.Encode(cars))

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 15, 2015 2:32 AM