2

i have class

    class abc{
       [JsonPropertyName("firstName")]
       public string FirstName{get; set;}

       [JsonPropertyName("lastName")]
       public string LastName{get; set;} }

i am assigning some values in it one method.

     public void DownloadJson(){
     abc abcModel= new abc(){ FirstName="Tom", LastName="Torres"};

     var test = JsonConvert.SerializeObject(abcModel);
     }

i want to save(download) this test object in json file on my browserwithout directing in new window just simply download it in same method DownloadJson() and in current window.

2
  • Is this asp.net core? Are you using MVC? Please provide more details. Otherwise it is too much infer. Commented Aug 25, 2020 at 22:38
  • yes it is .net core. Commented Aug 26, 2020 at 10:35

2 Answers 2

2

it worked.

   fileName="xyz.json"

   byte[] bytes = System.Text.Encoding.UTF8.GetBytes(test);

   var content = new System.IO.MemoryStream(bytes);
   return File(content , "application/json", fileName);
Sign up to request clarification or add additional context in comments.

Comments

1
public ContentResult DownloadJson(){
 var builder = new StringBuilder();
 abc abcModel= new abc(){ FirstName="Tom", LastName="Torres"};
 var test = JsonConvert.SerializeObject(abcModel);
 builder.Append($"{test}")
 var fileName = "someName.JSON";

        Response.Headers.Add("Content-Disposition", $"attachment; filename=\"{fileName}\"");

        return Content(data, "text/plain");

 }

have you tried returning a ContentResult?

1 Comment

Why not return Json(abcModel)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.