Bhavesh23 says:
[HttpGet]
Bhavesh23 says:
type:
"POST"
,
Here the issue is HttpGet attrubute and Ajax type POST.
You need to change Ajax type to GET.
Refer the below example.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
appsettings.json
"ConnectionStrings": {
"MyConn": "Data Source=.\\SQL2022;Initial Catalog=Northwind;uid=sa;pwd=pass@123;Trusted_Connection=True;TrustServerCertificate=true"
}
program.cs
using EF_Core_6_MVC;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Enabling MVC
builder.Services.AddControllersWithViews().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
string conStr = builder.Configuration.GetSection("ConnectionStrings")["MyConn"];
builder.Services.AddDbContext<DBCtx>(options => options.UseSqlServer(conStr));
var app = builder.Build();
//Configuring Routes
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Model
public class CustomerModel
{
[Key]
public string CustomerID { get; set; }
public string ContactName { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
Controller
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
API Controller
using EF_Core_6_MVC.Models;
using Microsoft.AspNetCore.Http;
using System.Xml.Linq;
using System.Data;
using Microsoft.Data.SqlClient;
using Microsoft.AspNetCore.Mvc;
namespace EF_Core_6_MVC.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AjaxAPIController : ControllerBase
{
private readonly IConfiguration _configuration;
public AjaxAPIController(IConfiguration configuration)
{
_configuration = configuration;
}
[Route("AjaxMethod")]
[HttpGet]
public List<CustomerModel> AjaxMethod()
{
List<CustomerModel> customers = new List<CustomerModel>();
string conStr = _configuration.GetConnectionString("MyConn");
using (SqlConnection connectionString = new SqlConnection(conStr))
{
connectionString.Open();
using (SqlCommand cmd = new SqlCommand("SELECT CustomerID,ContactName,City,Country FROM Customers", connectionString))
{
cmd.CommandType = CommandType.Text;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
CustomerModel customer = new CustomerModel
{
CustomerID = reader.GetString(0),
ContactName = reader.GetString(1),
City = reader.GetString(2),
Country = reader.GetString(3)
};
customers.Add(customer);
}
}
connectionString.Close();
}
return customers;
}
}
}
View
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<style type="text/css">
body { font-family: Arial; font-size: 10pt; }
</style>
</head>
<body class="container">
<div class="row">
<div class="card">
<div class="card-header">
<h3>Customer Records</h3>
</div>
<div class="card-body">
<table id="dataTableRecords" class="display" style="width:100%">
<thead>
<tr>
<th>CustomerId</th>
<th>Name</th>
<th>City</th>
<th>Country</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous" />
<script type="text/javascript">
$(function () {
$.ajax({
type: "GET",
url: "/api/AjaxAPI/AjaxMethod",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
function OnSuccess(response) {
$("#dataTableRecords").DataTable({
bLengthChange: true,
lengthMenu: [[5, 10, -1], [5, 10, "All"]],
bFilter: true,
bSort: true,
bPaginate: true,
data: response,
columns: [
{ "data": "CustomerID", "name": "CustomerID" },
{ "data": "ContactName", "name": "ContactName" },
{ "data": "City", "name": "City" },
{ "data": "Country", "name": "Country" }
]
});
}
</script>
</body>
</html>
Screenshot