0

My Download Method in Controller is

public FileResult GenerateJSON()
{
    string filename = "aa.json";
    string filepath = VariableDeclarations.wwwPath + @"\Downloads\" + filename;
    string filedata = System.IO.File.ReadAllText(filepath);
    string contentType = GetContentType(filepath);

    var cd = new System.Net.Mime.ContentDisposition
    {
        FileName = filename,
        Inline = true
            
    };

    HttpContext.Response.Headers.Add("Content-Disposition",$"attachment;filename=aa.json");

    return File(filedata, "application/json", filename);
}

and View Code is On button Click

function OnClickbtn() {
   

        $.ajax({
        type: "POST",
        url: vGenerateUrl,
        data: { },
        success: function(s) {
            DevExpress.ui.notify({ message: "xyz Generated", width: 1300 }, vSuccessMsgType, 3000);
        },
        error: function(result) {
            onAjaxError(result);
        }
        });
}

On Button click from my view a .json file is generated and i need to download that .json file should be downloaded in browser but after multiple efforts for changing it from actionresult, contentresult and fileresult I am still not able to download a file in my browser.

what changes do I need to make in the above code to download .json file in browser?

  • Have you tried to return `ContentResult` with JSON and content-type and set `Content-Disposition` in Response headers? – Farshan Jul 06 '22 at 07:01
  • `HttpContext.Response.Headers.Add("Content-Disposition", $"attachment;filename=aa.json");` and `return Content(json, "application/json");` might work. – Farshan Jul 06 '22 at 07:04

1 Answers1

0

Below is a demo about download .json file in browser, you can refer to it.

in the view:

<input type="button" value="Download Json" onclick="DownloadJson()" />
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript">
        function DownloadJson() {
            var studentList = [
                { "Name": "John", "score": "30" },
                { "Name": "Rozi", "score": "40" },
                { "Name": "Peter", "score": "50" },
                { "Name": "Finch", "score": "60" },
                { "Name": "Ravi", "score": "70" }
            ];
            //Convert JSON Array to string.
            var json = JSON.stringify(studentList);
            var blob = new Blob([json]);
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = "studentList.json";
            link.click();
        }
    </script>

result:

enter image description here

Or

public FileContentResult DownloadMission()
        {
            Mission toDownload = new Mission { Id = 1, name = "test" };
            string jsonString = JsonSerializer.Serialize(toDownload);
            var fileName = "test.json";
            var mimeType = "text/plain";
            var fileBytes = Encoding.ASCII.GetBytes(jsonString);
            return new FileContentResult(fileBytes, mimeType)
            {
                FileDownloadName = fileName
            };
        }

Mission

  public class Mission
    {
        public int Id { get; set; }
        public string name { get; set; }
    }

result:

enter image description here

Qing Guo
  • 6,041
  • 1
  • 2
  • 10
  • Thanks for your answer. I tried your controller code but was not able to get the desired result. It does not show any error but it also does not show file in downloads. Could you please suggest anything else? – Prathamesh Pitale Jul 06 '22 at 08:54
  • @PrathameshPitale My controller code doesn't use ajax , just a get method . – Qing Guo Jul 06 '22 at 09:24
  • I need to send some Parameters from view to generate JSON that is why i need to use Ajax. DO you think AJAX is creating any issues? – Prathamesh Pitale Jul 06 '22 at 09:31
  • @PrathameshPitale If you use ajax you cannot return file directly, you should do something in success function, because the broswer cannot recognize what you have returned. – Qing Guo Jul 06 '22 at 09:35
  • Read [this answer](https://stackoverflow.com/questions/72104653/file-not-downloading-on-ajax-post-response-net-core/72122511#72122511)to know more. – Qing Guo Jul 06 '22 at 09:42
  • Hi @Prathamesh Pitale, any update? If my answer help you resolve your issue, could you please accept as answer? If not, could you please follow up to let me know? Refer to:[How to access an answer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235) Thanks. – Qing Guo Jul 28 '22 at 02:10