I am trying to populate a datatable with data from SQL database. I have the following C# code which does return the correct number of records.
public class myClass
{
public int CenterID { get; set; }
public string CenterName { get; set; }
public string LicenseKey { get; set; }
public DateTime ExpiryDate { get; set; }
public string YearID { get; set; }
public DateTime Date { get; set; }
}
[WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
public static List<myClass> Bind()
{
SqlConnection con = new SqlConnection(
WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);
con.Open();
List<myClass> newClass = new List<myClass>();
SqlDataReader rdr = null;
SqlCommand cmd = new SqlCommand("zCenterDetails_get", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
newClass.Add(new myClass
{
CenterID = Convert.ToInt32(rdr["CenterID"]),
CenterName = rdr["CenterName"].ToString(),
LicenseKey = rdr["LicenseKey"].ToString(),
ExpiryDate = Convert.ToDateTime(rdr["ExpiryDate"]),
YearID = rdr["YearID"].ToString(),
Date = Convert.ToDateTime(rdr["Date"]),
});
}
con.Close();
return newClass;
}
The thing that I am struggling with is binding the data with AJAX. This is what I've tried so far but I know it is not correct. Please assist me to get my data into the datatable as I am new to datatables. Thanks
This is what I have so far:
function Bind() {
$.ajax({
type: "GET",
url: "WebForm1.aspx/Bind",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$('#datatable').DataTable({
data: data,
columns: [
{ 'data': 'CenterID' },
{ 'data': 'CenterName' },
{ 'data': 'LicenseKey' },
{ 'data': 'ExpiryDate' },
{ 'data': 'YearID' },
{ 'data': 'Date' }
]
});
}
});
}
Related
I am trying to populate a chart with test data before using production data but I cannot get the data into the chart. I do not have any errors that I can find and the controller is returning 2 complete datasets on the return Json(_chart);. The chart displays but there is no data in the chart. What am I doing wrong here?
index.cshtml
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<script type="text/javascript">
jQuery.extend({
getValues: function (url) {
var result = null;
$.ajax({
url: url,
type: 'get',
contentType: "application/json; charset=utf-8",
dataType: 'json',
async: false,
sucess: function (data) {
result = data;
}
});
return result;
}
});
</script>
</head>
<body>
<canvas id="myLineChart" width="400" height="200"></canvas>
<script type="text/javascript">
var ctx = document.getElementById("myLineChart").getContext('2d');
var tData = $.getValues("/Home/MultiLineChartDataEF");
var myLineChart = new Chart(ctx, {
type: 'line',
data: tData
});
</script>
</body>
HomeController.cs
public JsonResult MultiLineChartDataEF()
{
var chartData = _context.ChartTests.ToList();
var uniqueProducts = from d in chartData orderby d.ProductName group d by d.ProductName into m select m.Key;
var uniqueMonths = from a in chartData orderby a.MonthNumber group a by a.Month into g select g.Key;
string[] cols = new string[] { "#FF0000", "#000000" };
int i = 0;
Chart _chart = new();
_chart.labels = uniqueMonths.ToArray();
_chart.datasets = new List<Datasets>();
List<Datasets> _dataSet = new();
foreach(var d in uniqueProducts)
{
var colors = new string[uniqueProducts.Count()];
for (int j = 0; j < colors.Length; j++) colors[j] = cols[i];
_dataSet.Add(new Datasets()
{
label = d,
data = (from a in chartData where a.ProductName == d select a.Amount).ToArray(),
backgroundColor = new string[] { cols[i] },
borderColor = new string[] { cols[i] },
borderWidth = "1"
});
i++;
}
_chart.datasets = _dataSet;
return Json(_chart);
}
Chart.cs
using System.Collections.Generic;
namespace ChartTest.Models
{
public class Chart
{
public string[] labels { get; set; }
public List<Datasets> datasets { get; set; }
}
public class Datasets
{
public string label { get; set; }
public string[] backgroundColor { get; set; }
public string[] borderColor { get; set; }
public string borderWidth { get; set; }
public string[] data { get; set; }
}
}
ChartTest.cs
namespace ChartTest.Models
{
public partial class ChartTest
{
public string ProductName { get; set; }
public string Month { get; set; }
public string Amount { get; set; }
public int? MonthNumber { get; set; }
}
}
I think it's just a spelling mistake of your ajax, the success of the Ajax call should be "success", not "sucess", after I corrected it, the data can be fetched normally.
jQuery.extend({
getValues: function (url) {
var result = null;
debugger;
$.ajax({
url: url,
type: 'get',
contentType: "application/json; charset=utf-8",
dataType: 'json',
async: false,
success: function (data) {
result=data;
},
error:function(){
return error;
}
});
return result;
}
});
Test Result:
When user select any value from drop down, then Ajax has to call server and return some values through JSON object.
Here is my Ajax code
//AJAX Security
$('#ddlSecurityLevel').change(function () {
if ($('#ddlSecurityLevel').val() !== 'None') {
$.ajax({
type: 'POST',
url: 'AjaxSecurity.aspx?securityLevelOrUser=SecurityLevel&SecurityKey=1&ReportName=TotalSales',
contentType: 'application/json; charset=utf-8',
data: 'json',
//dataType: JSON.stringify(Data),
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
//alert("hello");
alert(result.d); // output UNDEFINED
}
function AjaxFailed(result) {
alert("Error");
alert(result.status + ' ' + result.statusText);
}
}
});
Asp.net C# code
public class GetResult
{
public string removedReportName { get; set; }
public string removedColumnNames { get; set; }
public string removedFilterNames { get; set; }
}
public partial class AjaxSecurity : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string securityLevelOrUser = Request["securityLevelOrUser"].ToString();
if (securityLevelOrUser.Equals("SecurityLevel"))
{
string jsonString = js.Serialize(getResultBySecurityLevel(Request["SecurityKey"], Request["ReportName"]));
Response.Write(jsonString);
}
else
{
}
}
private GetResult getResultBySecurityLevel(string securityLevel,string reportName)
{
GetResult getResult = new GetResult();
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ReportHide,RColumnName,RFilterName FROM SecurityLevelDetails WHERE SecurityLevel=#SecurityLevel and ReportName=#ReportName";
cmd.Parameters.AddWithValue("#ReportName", reportName);
cmd.Parameters.AddWithValue("#SecurityLevel", securityLevel);
con.Open();
SqlDataReader rd=cmd.ExecuteReader();
while(rd.Read())
{
getResult.removedReportName = rd["ReportHide"].ToString();
getResult.removedColumnNames = rd["RColumnName"].ToString();
getResult.removedFilterNames = rd["RFilterName"].ToString();
}
}
return getResult;
}
}
When I run my Asp.net code with following parameter, It returns values in browser
URL
http://localhost:55047/AjaxSecurity.aspx?securityLevelOrUser=SecurityLevel&SecurityKey=4&ReportName=TotalSales
Response.Write
{"removedReportName":"1","removedColumnNames":"ItemLookupCode,Department","removedFilterNames":"ExtendedDescription,DepartmentName"}
But the output alert is Undefined
Comment data:'json' and Remove d from alert(result.d);
To access the data in js alert you can write like this,
function AjaxSucceeded(result) {
if(result!=null)
{
alert(result[0].removedReportName +"," result[0].removedColumnNames);
}
}
In your Page_Load method, you need to clear out the output and write your own,
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(jsonString);
Response.End();
Please check this link, this is what you need
I Am trying to fetch the data from database and display it in the page using ajax and jquery. Am new to this platform so can anyone help me
Model:
public class EmployeeModel
{
public int EmpId { get; set; }
public string EmpName { get; set; }
public int Age { get; set; }
public int Salary { get; set; }
}
Controller :
private static readonly string connectionString = ConfigurationManager.ConnectionStrings["ConnStringDb1"].ConnectionString;
public ActionResult GetUser()
{
return View();
}
public JsonResult GetAllUser(int EmpId)
{
List<EmployeeModel> employee = new List<EmployeeModel>();
string query = string.Format("Select * From Employee", EmpId);
SqlConnection connection = new SqlConnection(connectionString);
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
employee.Add(
new EmployeeModel
{
EmpId = int.Parse(reader["EmpId"].ToString()),
EmpName = reader.GetValue(0).ToString(),
Age = int.Parse(reader["Age"].ToString()),
Salary = int.Parse(reader["Salary"].ToString())
}
);
}
}
return Json(employee, JsonRequestBehavior.AllowGet);
}
}
ajax:
#{
ViewBag.Title = "Home Page";
var EmployeeModel = (List<second_day.Models.EmployeeModel>)Model;
}
<div id="id"></div>
<div id="firstName"></div>
<div id="lastName"></div>
<p id="getEmployee">Get Employee</p>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('p#getEmployee').click(function () {
GetEmployeeUsingAjax();
});
});
function GetEmployeeUsingAjax() {
$.ajax({
type: 'GET',
url: '#Url.Action("GetAllUser")',
data:{"EmpId":EmpId},
dataType: 'json',
success: function (data) {
console.log(data);
//$('#id').text(emp.employee.Id);
//$('#firstName').text(emp.employee.FirstName);
//$('#lastName').text(emp.employee.LastName);
},
error: function (emp) {
alert('error');
}
});
}
Here i Need to fetch the data when its success else through error if it doesnt
Am new to this platform can anyone help me
function GetEmployeeUsingAjax() {
var EmpId = 2;
$.ajax({
type: 'GET',
url: '#Url.Action("GetAllUser")',
data: { "EmpId": EmpId },
dataType: 'json',
success: function (data) {
alert(data);
//$('#id').text(emp.employee.Id);
//$('#firstName').text(emp.employee.FirstName);
//$('#lastName').text(emp.employee.LastName);
},
error: function (emp) {
alert('error');
}
});
}
[HttpGet]
public JsonResult GetAllUser(int EmpId)
{
// your code
}
plus string.Format("Select * From Employee where empid = {0} ",EmpId)
Please Check Below code :
var var EmpId = 2;
var abc = {
"EmpId": EmpId
};
$.ajax(
{
url: '/ControllerName/GetAllUser/',
type: "GET",
async: false,
dataType: "json",
contentType: "application/json;",
data: JSON.stringify(abc),
success: function (result) {
alert(data);
}
});
And Action Should Be :
[HttpGet]
public JsonResult GetAllUser(int EmpId)
{
}
Happy !!
I can't seem to figure out how to get my Javascript object to bind to my model that is (as far as I can tell) just like it as far as properties go.
First the Javascript Object creation:
var transDetail = new Object();
transDetail.TransactionDetailID = transdetailId;
transDetail.TransactionID = "";
transDetail.Year = new Date().getFullYear();
transDetail.Volume = "";
transDetail.UnitPrice = "";
transDetail.TransferableVolume = "";
transDetail.Credits = "";
transDetail.Shares = "";
transDetail.DollarsPerShare = "";
It is then passed to this javascript function
function loadTransDetailEditCreate(d, cb, title, transactionDetail) {
$.ajax(
{
url: '/TransactionDetail/LoadEditCreate',
data: JSON.stringify(transactionDetail),
dataType: 'json',
success: function (result) {
d.html(result);
CreateEditTransDetail(d, cb, title, transactionDetail);
d.dialog('open');
}
}
);
}
I've verified that the year property before transmission is filled with 2015.
Now the model definition
public partial class TransactionDetail
{
public int TransactionDetailID { get; set; }
public int TransactionID { get; set; }
public int Year { get; set; }
public Nullable<int> Volume { get; set; }
public Nullable<int> UnitPrice { get; set; }
public Nullable<int> TransferableVolume { get; set; }
public Nullable<int> Credits { get; set; }
public Nullable<int> Shares { get; set; }
public Nullable<int> DollarsPerShare { get; set; }
}
And the Action definition
public PartialViewResult LoadEditCreate(TransactionDetail transactionDetail)
When I break first thing into the action all non nullable ints are set to 0 and all nullable are set to null.
The problem is with sending the data: JSON...
You have 2 options:
use POST: (tried and works)
function loadTransDetailEditCreate(d, cb, title, transactionDetail) {
$.ajax(
{
type: 'post', //added
contentType: "application/json; charset=utf-8", //added
url: '/TransactionDetail/LoadEditCreate',
data: JSON.stringify(transactionDetail),
dataType: 'json',
success: function (result) {
d.html(result);
CreateEditTransDetail(d, cb, title, transactionDetail);
d.dialog('open');
}
}
);
}
and decorate your controller with [HttpPost] attribute
[HttpPost]
public PartialViewResult LoadEditCreate(TransactionDetail transactionDetail)
If you want to use get - look here (didn't try, should work)
Until now, I've been successfully passing an array of strings to my controller via AJAX using JSON.stringify.
However, now I need to move that array into another object in order to pass more data to the AJAX call.
The following (and many other attempts) result in the jobRequest.Tests having no members when passed to the controller:
function executeTests(testsToRun) {
if (testsToRun.length > 0) {
var jobRequest = new Object;
jobRequest.SampleTitle = '#ViewBag.SampleTitle';
jobRequest.SampleLanguage = '#ViewBag.SampleLanguage';
jobRequest.Mode = '#ViewBag.SampleMode';
jobRequest.Tests = JSON.stringify(testsToRun);
$.ajax({
url: '#Url.Action("ProcessJob", "ProcessJob")',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ 'jobRequest': jobRequest }),
success: function (jobId) {
window.location.href = '#Url.Action("Index", "ProcessJob")' + '?id=' + jobId;
}
});
}
}
public class JobRequest
{
public string SampleTitle { get; set; }
public string SampleLanguage { get; set; }
public string Mode { get; set; }
public List<string> Tests = new List<string>();
}
public JsonResult ProcessJob(JobRequest jobRequest)
{
...
You can change the class JobRequest like this:
public class JobRequest
{
public string SampleTitle { get; set; }
public string SampleLanguage { get; set; }
public string Mode { get; set; }
public List<string> Tests { get; set; }
}
and remove the JSON.stringify in the array:
jobRequest.Tests = testsToRun;