Hi KatieNgoc,
Please refer below Sample.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
You can download the database table SQL by clicking the download link below.
Download SQL file
Model
public class PersonModel
{
public int CustomerId { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
Namespaces
using System.Data.SqlClient;
using System.Configuration;
using Newtonsoft.Json;
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult AjaxMethod()
{
List<PersonModel> persons = new List<PersonModel>();
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, Name, Country FROM Customers", con))
{
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
PersonModel model = new PersonModel();
model.CustomerId = Convert.ToInt32(sdr["CustomerId"]);
model.Name = Convert.ToString(sdr["Name"]);
model.Country = Convert.ToString(sdr["Country"]);
persons.Add(model);
}
}
con.Close();
}
}
return Json(persons);
}
}
View
@model jQuery_AJAX_MVC.Models.PersonModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<input type="button" id="btnGet" value="Get JSON" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnGet").click(function () {
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//Convert JSON Array to string.
var json = JSON.stringify(persons);
//Convert JSON string to BLOB.
json = [json];
var blob1 = new Blob(json, { type: "text/plain;charset=utf-8" });
//Check the Browser.
var isIE = false || !!document.documentMode;
if (isIE) {
window.navigator.msSaveBlob(blob1, "persons.txt");
} else {
var url = window.URL || window.webkitURL;
link = url.createObjectURL(blob1);
var a = $("<a />");
a.attr("download", "persons.txt");
a.attr("href", link);
$("body").append(a);
a[0].click();
$("body").remove(a);
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
</body>
</html>
Screenshot(GeneratedJSON)