This is in addition to my article CRUD in single View. You can find the details of the class library, which I had used here.
For creating a JSON file, create a simple MVC project.
- Add a Contoller to your project.
- Add an ActionResult method, named as Index in your controller.
- Now, add a view to the Index and do the following steps in your view.
- @model IEnumerable<JsonEntity.Users>
- //JsonEntity is my Class library whose reference is added to my project
- //Users is my Model which i had added to my class library
- @{
- ViewBag.Title = "Index";
- }
- <h2>Index</h2>
- <script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
- <p>
- <input type="button" id="btnCreateJson" value="Create Json" class="btn btn-default"/>
- </p>
- $("#btnCreateJson").click(function () {
- $.post("/Users/CreateJson", function (response) { //Users is my controller's Name and CreateJson is my Jsonresult Method
- if (response != null) {
- alert("Json Created");
- location.reload();
- }
- else {
- alert("Error");
- }
- });
- })
- [HttpPost]
- public ActionResult CreateJson()
- {
- try
- {
- using (JsonContext context = new JsonContext()) //JsonContext is my context name which i had used in class library
- {
- var UsersList = context.ObjUser.ToList(); // Getting the list of users for DB.
- var jsondata = new JavaScriptSerializer().Serialize(UsersList);
- string path = Server.MapPath("~/Json/"); //Path where your json file will be saved
- System.IO.File.WriteAllText(path + "User.json", jsondata); // User.json is your json file's name
- return Json(UsersList, JsonRequestBehaviour.AllowGet);
- }
- }
- catch(Exception ez)
- {
- return null;
- }
- }

Join the conversation! Your thoughts help the community grow.