C# in javascript executes only once - javascript

When I try to read the data from Azure Database code does so correctly on page load/refresh but then it repeats the very same data, even though I call a function to get a new one.
C# Code for fetching data.
public static class GetSensorData
{
public static List<Reading> GetTemperatureSensorData(int quantity)
{
decimal TemperatureCelcius;
DateTime TimeOfAReading;
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["rpiDB"].ConnectionString.ToString();
List<Reading> TempTemperatureList = new List<Reading> { };
SqlConnection Connection = new SqlConnection(ConnectionString);
SqlCommand GetTemperature = new SqlCommand("SELECT TOP " + quantity + " * FROM tbl_temp ORDER BY time DESC;", Connection);
Connection.Open();
SqlDataAdapter TempAdapter = new SqlDataAdapter(GetTemperature);
DataTable TempereatureSensorDataTable = new DataTable();
TempAdapter.Fill(TempereatureSensorDataTable);
for (int i = 0; i < quantity; i++)
{
TemperatureCelcius = (decimal)TempereatureSensorDataTable.Rows[i][0];
//gotta change the culture from within
TemperatureCelcius = decimal.Parse(TemperatureCelcius.ToString(), CultureInfo.InvariantCulture);
TimeOfAReading = (DateTime)TempereatureSensorDataTable.Rows[i][1];
TempTemperatureList.Add(new Reading(TemperatureCelcius, TimeOfAReading.ToString("HH/mm")));
}
Connection.Close();
return TempTemperatureList;
}
}
And here's how I use it in CSHTML
var updateData = function (oldData) {
var labels = oldData["labels"];
var dataSetA = oldData["datasets"][0]["data"];
#{
List<Reading> SingleReading = new List<Reading>(GetSensorData.GetTemperatureSensorData(1));
}
var datetime = #SingleReading[0].TimeOfReading
labels.push(String(datetime));
labels.shift();
var Temperature = #(SingleReading[0].TemperatureCelcius);
dataSetA.push(Temperature / 100);
dataSetA.shift();
};
setInterval(function () {
updateData(data);
myLineChart.data = data;
myLineChart.update();
}, 5000
);
The function in setInterval is being executed every 5 seconds but with the data, I got on the page load.

You need to create a web service in your C# project so that you can make AJAX calls to GetTemperatureSensorData. I recommend putting this into its own Web API project. https://msdn.microsoft.com/en-us/library/hh833994(v=vs.108).aspx
Next, you will need to create an AJAX call to the web service in your javascript code. To make this easier to do, I recommend using the jQuery library, specifically the get command: https://api.jquery.com/jquery.get/

Thanks everyone for your help, I've figured it out.
This is my CS code from HomeController.cs
public ActionResult GetTemp(int quantity)
{
decimal TemperatureCelcius;
DateTime TimeOfReading;
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["rpiDB"].ConnectionString.ToString();
List<Reading> TempTemperatureList = new List<Reading> { };
SqlConnection Connection = new SqlConnection(ConnectionString);
SqlCommand GetTemperature = new SqlCommand("SELECT TOP " + quantity + " * FROM tbl_temp ORDER BY time DESC;", Connection);
Connection.Open();
SqlDataAdapter TempAdapter = new SqlDataAdapter(GetTemperature);
DataTable TempereatureSensorDataTable = new DataTable();
TempAdapter.Fill(TempereatureSensorDataTable);
for (int i = 0; i < quantity; i++)
{
TemperatureCelcius = (decimal)TempereatureSensorDataTable.Rows[i][0];
TimeOfReading = (DateTime)TempereatureSensorDataTable.Rows[i][1];
TempTemperatureList.Add(new Reading(TemperatureCelcius, TimeOfReading.ToString("HH:mm")));
}
Connection.Close();
return Json(TempTemperatureList, JsonRequestBehavior.AllowGet);
}
And Ajax:
setInterval(function () {
$.ajax({
type: 'GET',
url: '/Home/GetTemp',
contentType: 'application/json; charset=utf-8',
data: { 'quantity': 1 },
success: function (response) {
var _Temperature = response[0].TemperatureCelcius;
var _TimeOfReading = response[0].TimeOfReading;
console.log(_Temperature);
updateData(data, _Temperature, _TimeOfReading);
myLineChart.data = data;
myLineChart.update();
},
error: function(req, err){ console.log('my message ' + err); }
});
}, 5000
);

Related

Event Not fire view to controller and not pass values in controller in mvc

I am sharing js code and controller code, when I enter values then I debug js code and show this values:
{"ReqID":"2","ReqNo":"000002","ReqDate":"21/09/2018","Job":"f","Approvedby":"f","IsApproved":"true","items":[{"Srno":"1","ItemCode":"018-0002","qty":"2","Remarks":"f"},{"Srno":"2","ItemCode":"028-0003","qty":"3","Remarks":"fff"},{"Srno":"3","ItemCode":"028-0010","qty":"7","Remarks":"ggg"}],"mSaveReq":"AddNew"}
but from the view to the controller the value is not passed, it only shows a js alert Error, I don't know what is the problem. The value passes correctly but why does this not pass the value to the controller?
Javascript
<script>
//Show model
function addNewOrder()
{
$("#NewOrderForm").modal();
}
// Add Multiple Record
$("#addToList").click(function (e) {
e.preventDefault();
if ($.trim($("#ItemCode").val()) == "" || $.trim($("#Qty").val()) == "" || $.trim($("#Remarks").val()) == "") return;
var Srno = document.getElementById("detailsTable").rows.length;
ItemCode = $("#ItemCode").val(),
qty = $("#Qty").val(),
Remarks = $("#Remarks").val(),
detailsTableBody = $("#detailsTable tbody");
var ReqItems = '<tr><td>' + Srno + '</td><td>' + ItemCode + '</td><td>' + qty + '</td><td>' + Remarks + '</td><td> <a data-itemId="0" href="#" class="deleteItem">Remove</a></td></tr>';
detailsTableBody.append(ReqItems);
clearItem();
});
//After Add A New Order In The List
function clearItem()
{
$("#ItemCode").val('');
$("#Qty").val('');
$("#Remarks").val('');
}
// After Add A New Order In The List, If You Want, You Can Remove
$(document).on('click', 'a.deleteItem', function (e)
{
e.preventDefault();
var $self = $(this);
if ($(this).attr('data-itemId') == "0") {
$(this).parents('tr').css("background-color", "white").fadeOut(800, function () {
$(this).remove();
});
}
});
//After Click Save Button Pass All Data View To Controller For Save Database
function saveRequisition(data) {
return $.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: "/Home/RequisitionInsert", // function save
data: data,
success: function (result) {
alert(result);
location.reload();
},
error: function () {
alert("Error!")
}
});
}
//Collect Multiple Order List For Pass To Controller
$("#saveRequisition").click(function (e)
{
e.preventDefault();
var requisitionArr = [];
requisitionArr.length = 0;
$.each($("#detailsTable tbody tr"), function () {
requisitionArr.push({
Srno: $(this).find('td:eq(0)').html(),
ItemCode: $(this).find('td:eq(1)').html(),
qty: $(this).find('td:eq(2)').html(),
Remarks: $(this).find('td:eq(3)').html()
});
});
var data = JSON.stringify({
ReqID: $("#ReqID").val(),
ReqNo: $("#ReqNo").val(),
ReqDate: $("#ReqDate").val(),
Job: $("#Job").val(),
Approvedby: $("#Approvedby").val(),
IsApproved: $("#IsApproved").val(),
items: requisitionArr,
mSaveReq: $("#mSaveReq").val()
});
$.when(saveRequisition(data)).then(function (response) {
console.log(response);
}).fail(function (err) {
console.log(err);
});
});
</script>
Controller
[HttpPost]
public ActionResult RequisitionInsert(string ReqID, string ReqNo,string ReqDate, string Job,string Approvedby,bool IsApproved, Requisition[] items, bool mSaveReq)
{
try
{
objclsRequisition.RequisitionInsert(ReqID, ReqNo,ReqDate, Job,Approvedby,IsApproved, items,mSaveReq);
ViewBag.Message = "Your record has been inserted Successfully";
ModelState.Clear();
return RedirectToAction("Requisition", "Home");
}
catch (Exception)
{
throw;
}
}
public int RequisitionInsert(string ReqID, string ReqNo, string ReqDate, string Job, string Approvedby, bool IsApproved, Requisition[] items, bool AddNew)
{
try
{
con.Open();
tr = con.BeginTransaction();
if (AddNew)
{
cmd = new SqlCommand("Select ISNULL(MAX(Req_ID), 0) + 1 from RequisitionMain", con);
ReqID = cmd.ExecuteScalar().ToString();
cmd = new SqlCommand("Select ISNULL(MAX(CAST(ReqNo as int)),0)+1 from RequisitionMain where Comp_ID=1 and GL_Year='2018-2019'", con);
ReqNo = cmd.ExecuteScalar().ToString().PadLeft(6, '0');
cmd = new SqlCommand("Sp_RequisitionMainInsert", con);
}
else
cmd = new SqlCommand("Sp_RequisitionMainUpdate", con);
cmd.Parameters.AddWithValue("#Req_ID", ReqID);
cmd.Parameters.AddWithValue("#ReqNo", ReqNo);
cmd.Parameters.AddWithValue("#Comp_ID", "1");
cmd.Parameters.AddWithValue("#GL_Year", "2018-2019");
cmd.Parameters.AddWithValue("#ReqDate", DateTime.Parse(ReqDate).ToString("yyyy-MM-dd"));
cmd.Parameters.AddWithValue("#Job", Job);
cmd.Parameters.AddWithValue("#ApprovedBy", Approvedby);
cmd.Parameters.AddWithValue("#UserName", System.Web.HttpContext.Current.Session["AgentName"]);
cmd.Parameters.AddWithValue("#IsApproved", IsApproved);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Transaction = tr;
cmd.ExecuteNonQuery();
string mRowState = "";
for (int i = 0; i < items.Length; i++)
{
if(mRowState == "Deleted")
{
cmd = new SqlCommand("delete from RequisitionDetail where Req_ID_Det=" + items[i].Req_ID_Det + "", con);
cmd.Transaction = tr;
cmd.ExecuteNonQuery();
continue;
}
if (mRowState == "Added")
{
cmd = new SqlCommand("Select ISNULL(MAX(Req_ID_Det), 0) + 1 from RequisitionDetail", con);
Int64 mReqID_Det = Convert.ToInt64(cmd.ExecuteScalar());
cmd = new SqlCommand("Sp_RequisitionDetailInsert", con);
cmd.Parameters.AddWithValue("#Req_ID_Det", mReqID_Det);
}
else if (mRowState == "Modified")
{
cmd = new SqlCommand("Sp_RequisitionDetailUpdate", con);
cmd.Parameters.AddWithValue("#Req_ID_Det", items[i].Req_ID_Det);
}
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Req_ID", ReqID);
cmd.Parameters.AddWithValue("#ReqNo", ReqNo);
cmd.Parameters.AddWithValue("#Comp_ID", "1");
cmd.Parameters.AddWithValue("#GL_Year", "2018-2019");
cmd.Parameters.AddWithValue("#SrNo", i + 1);
cmd.Parameters.AddWithValue("#ItemCode", items[i].ItemCode);
cmd.Parameters.AddWithValue("#Qty", Convert.ToDecimal(items[i].Qty));
cmd.Parameters.AddWithValue("#Remarks", items[i].Remarks);
cmd.Transaction = tr;
cmd.ExecuteNonQuery();
}
tr.Commit();
return i;
}
catch (SqlException sqlex)
{
tr.Rollback();
throw sqlex; // read all sql error
}
catch (Exception ex)
{
tr.Rollback();
throw ex; // General execption
}
finally
{
con.Close();
}
}

Not able to load the Gridview on Load

I am not able to load the gridview on page load. It keeps giving me
Uncaught TypeError: Cannot read property 'length' of undefined.
I have mnetioned the code and the handler beneath. Please help me solve the issue. The issue happens in the Jquery.
<script type="text/javascript">
$(document).ready(function () {
BindGridView();
});
function BindGridView() {
$.ajax({
type: "POST",
url: "../Pm/uc/G.ashx/GetMailDetail",
contentType: "application/json;charset=utf-8",
data: {},
dataType: "json",
success: function (data) {
if (data.d.length > 0) {
$("#grdDemo").append("<tr><th>Username</th></tr>");
for (var i = 0; i < data.d.length; i++) {
$("#grdDemo").append("<tr><td>" +
data.d[i].Username + "</td> <td>");
}
}
},
error: function (result) {
}
});
}
</script>
<asp:GridView ID="grdDemo" runat="server">
</asp:GridView>
This is in the Handler.( You can replace the query with anything.)
public void ProcessRequest(HttpContext context)
{
//int mailid = int.Parse(context.Request["mid"]);
//var detail = GetMailDetail(mailid);
var detail = GetMailDetail();
if (detail != null)
{
context.Response.ContentType = "application/json";
string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(detail);
context.Response.Write(json);
}
else
{
context.Response.StatusCode = 404;
}
}
//protected object GetMailDetail(int mailid)
protected object GetMailDetail()
{
List<DetailsClass> Detail = new List<DetailsClass>();
Connection Con = new Connection();
String Connection = Con.Active_Connection();
SqlConnection con = new SqlConnection(Connection);
con.Open();
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("select Sp4_Txt from Sp4", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dtGetData = new DataTable();
da.Fill(dtGetData);
foreach (DataRow dtRow in dtGetData.Rows)
{
DetailsClass DataObj = new DetailsClass();
DataObj.Username = dtRow["Sp4_Txt"].ToString();
Detail.Add(DataObj);
}
return Detail.ToArray();
}
public class DetailsClass //Class for binding data
{
public string Username { get; set; }
}
public bool IsReusable
{
get
{
return false;
}
}
}
Cannot read property 'length' of undefined.
This error is coming because you are accessing the data.d without checking data and accessing data.d.length without checking data.d
Do something like this:
if(data){
if(data.d){
if (data.d.length > 0) {
$("#grdDemo").append("<tr><th>Username</th></tr>");
for (var i = 0; i < data.d.length; i++) {
$("#grdDemo").append("<tr><td>" +
data.d[i].Username + "</td> <td>");
}
}
}
}

DateTime is not displayed as expected [duplicate]

This question already has answers here:
Javascript serialization of DateTime in asp.net is not giving a javascript date object?
(10 answers)
Closed 6 years ago.
I have a C# code to get some dates from a Sql Table, these dates are filled by mssql getdate() the problem here is that my dates are displayed in the following structure:
/Date(1480343496517)/
And what I expect is this:
2016-11-28 08:13:23.820 //This is what I get executing my query in MSSQL
This is my full code:
C# Class
public MyDate(DateTime date)
{
Date = date;
}
public DateTime Date { get; set; }
WebMethod
[WebMethod]
public string ShowDate()
{
DataTable dt = new DataTable();
dt = conn.CheckTable("date");
MyDate fch;
List<MyDate> list = new List<MyDate>();
for (int i = 0; i < dt.Rows.Count; i++)
{
fch = new Fecha();
fch.Date = Convert.ToDateTime(dt.Rows[i]["Date"]);
list.Add(fch);
fch = null;
}
JavaScriptSerializer js = new JavaScriptSerializer();
string lines = js.Serialize(list);
return lines;
}
CheckTable
public DataTable CheckTable(string table)
{
dt = new DataTable();
ds = new DataSet();
string sql = "";
switch (table)
{
case "date":
sql = "SELECT Date FROM dbo.Table_1";
break;
}
try
{
Open();
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(ds);
dt = ds.Tables[0];
}
catch (Exception ex)
{
}
finally
{
Close();
}
return dt;
}
And my JS function:
$.ajax({
type: 'POST', //POST | GET
url: "WebService.asmx/ShowDate", //Direccion del ws
dataType: 'json',
contentType: 'application/json',
timeout: 600000,
error: function (xhr) {
$('#dates').html('<option>Error</option>');
},
success: function (data) {
var datas = JSON.parse(data.d);
for (var i = 0; i < datos.length; i++) {
var myDate= datas[i].Date;
options += '<option value ="' + myDate+ '">';
options += myDate;
options += '</option>';
}
$('#dates').html(options);
}
});
What I'm doing wrong and what can I do to solve it?
I don't know what the other classes you're using are, but if you just want a list of dates from the query then this should do it...
[WebMethod]
public string ShowDate()
{
DataTable dt = new DataTable();
dt = conn.CheckTable("date");
List<DateTime> list = new List<DateTime>();
for (int i = 0; i < dt.Rows.Count; i++)
{
list.Add(Convert.ToDateTime(dt.Rows[i]["Date"]).ToString());
}
JavaScriptSerializer js = new JavaScriptSerializer();
string lines = js.Serialize(list);
return lines;
}
then in the JavaScript, change this one line...
var myDate = datas[i];
The web method will now just return a serialised list of dates, so no need to get a .date property of the list objects any more.

How to convert datatable to json string in c#

Its work perfect when data in the datatable is small i.e 10 columns and 300 rows. But when the amount of data in datatable is large it did not work.
Here is my code
[WebMethod]
public static string getData()
{
string _cs = "";
string _query = "";
OleDbConnection _conn = new OleDbConnection();
OleDbCommand _cmd = new OleDbCommand();
OleDbDataAdapter _da = new OleDbDataAdapter();
DataTable _dt = new DataTable();
try
{
_cs = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _path + ";Extended Properties= \"Excel 8.0;HDR=Yes;IMEX=1\";";
//_query = "SELECT * FROM [3123121288$A1:L290]"; work perfect
_query = "SELECT * FROM [3123121288$]"; //did not work
_conn.ConnectionString = _cs;
_cmd.Connection = _conn;
_cmd.CommandText = _query;
_da.SelectCommand = _cmd;
_da.Fill(_dt);
}
catch (Exception ex)
{ }
return JsonConvert.SerializeObject(_dt);
}

Trying to sort repeater rows with this jQuery

I am trying to sort repeater rows with this jquery . But I am not able to save sort items. Please help me . how can save sorting in database as well as in .aspx page?Thank you in advance
<script language="javascript" type="text/javascript">
$("#defaultList").sortable();
$(document).ready(function () {
$("#defaultList").sortable(
{
update: function (ev, ui) {
var result = $('#defaultList').sortable('toArray');
updateSequenceNumber(result);
}
}
);
});
function updateSequenceNumber(items) {
var originalIdAndSequenceNumber = '';
var index = 0;
for (i = 0; i <= items.length - 1; i++) {
if (items[i].length == 0)
continue;
var item = $('#' + items[i])[0];
originalIdAndSequenceNumber += item.attributes["originalId"].nodeValue + ":" + index.toString();
originalIdAndSequenceNumber += "|";
index = index + 1;
}
persistPositionUsingAjax(originalIdAndSequenceNumber);
}
function persistPositionUsingAjax(originalIdAndSequenceNumber) {
$.ajax(
{
type: "POST",
dataType: "text",
url: "AjaxService.asmx/UpdateSequenceNumber",
data: "s=" + originalIdAndSequenceNumber,
success: function (response) {
}
}
);
}
my ajax method:
[WebMethod]
public string UpdateSequenceNumber(string s)
{
s = s.TrimEnd('|');
string updateQuery = #"update dnn_Table_1 set SortId = {0}
where ImageId = {1}";
StringBuilder sb = new StringBuilder();
string[] originalIdAndSeqNumberArray = s.Split('|');
foreach (var originalIdAndSeqNumberCombined in originalIdAndSeqNumberArray)
{
var tempArray = originalIdAndSeqNumberCombined.Split(':');
int originalId = Convert.ToInt32(tempArray[0]);
int sequenceNumber = Convert.ToInt32(tempArray[1]);
sb.Append(String.Format(updateQuery, sequenceNumber, originalId));
sb.Append(System.Environment.NewLine);
}
UpdateInDatabase(sb.ToString());
return "Hello World";
}
private void UpdateInDatabase(string updateQuery)
{
SqlDataProvider sqd = new SqlDataProvider();
string ConnectionString = sqd.ConnectionString;
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand(updateQuery, conn);
command.CommandText = updateQuery;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
What status code does the ajax call return?
To me it looks like a 500. You are building an update statement that after a few iterations will look something like this
update dnn_Table_1 set SortId = 3 where ImageId = 2update dnn_Table_1 set SortId = 2 where ImageId = 4update dnn_Table_1 set SortId = 7 where ImageId = 6
That just won't work. Try eihter constructing the SQL update differently or move UpdateInDatabase into the foreach loop.
There might be other issues which I didn't spot, but this might be a starting point.
Hope that helps

Categories

Resources