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.
Related
I have two text boxes that are enabled based on a checkbox. If checked == true then enable editing. Until this point everything is fine. However, when I hit the Submit button to save it to the database, it's not working. I was able to save it with just one of the text boxes being editable. Now that I have two editable boxes, it's not working.
Problem:
The ajax call is sending the dates and the ID back to the controller method. However, it's not getting saved to the DB. In UpdatePlannedDate I put in a couple breakpoints, its completely skipping over the first forEach loop.
The Exception it's throwing:
String was not recognized as a valid DateTime.
Model Class:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? Date1{ get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? Date2{ get; set; }
public string R_ID { get; set; }
public string U_ID { get; set; }
public string C_ID { get; set; }
Controller class:
[HttpPost]
public JsonResult UpdatePlannedDate(string ids, string Date1, string Date2)
{
model = new Hello();
Entity db = new Entity();
List<Hello> list = new List<Hello>();
string[] IDS = ids.Split(',');
string[] Date1S = Date1.Split(',');
string[] Date2S = Date2.Split(',');
try
{
for (int i = 0; i < IDS.Length; i++)
{
if (IDS[i] != null && IDS[i] != "")
{
Hello item = new Hello { R_ID = IDS[i], Date_Two = DateTime.Parse(Date2S[i]), Date_One = DateTime.Parse(Date1S[i]) };
list.Add(item);
}
}
foreach (var row in db.table1)
{
foreach (var row2 in db.table2)
{
if (row.U_ID == row2.C_ID)
{
foreach (var item in list)
{
if (row.U_ID == item.R_ID)
{
var cd = db.Table2.Where(x => x.C_ID == row.U_ID).First();
cd.PlanDate = Convert.ToDateTime(item.Date_Two);
cd.PlanDate = Convert.ToDateTime(item.Date_One);
}
}
}
}
}
db.SaveChanges();
return Json(new { success = true, msg = "Updated" });
}
catch (Exception ex)
{
return Json(new { success = false, msg = ex.Message });
}
}
View class:
$(document).ready(function () {
var ids = "";
var date1 = "";
var date2 = "";
//Save to DB
$("#btnSubmit").bind("click", function () {
createUpdateArrays();
var url = "/Sample/UpdatePlannedDate";
$.ajax({
type: "POST",
url: url,
data: { ids: ids, date1: date1, date2: date2 },
success: function (data) {
if (data.success) {
$('.msg').html('Updated');
}
else {
alert("error");
}
}
});
ids = "";
date1 = "";
date2 = "";
});
function createUpdateArrays() {
var i = 0;
$('input.remedy-id:checkbox').each(function () {
if ($(this).is(':checked')) {
var rid = $(this).attr("id");
$('.date2').each(function () {
var did = $(this).attr("id");
if (did === rid) {
var date_2 = $(this).val();
ids += rid + ",";
date2 += date_2 + ",";
}
});
$('.date1').each(function () {
var tid = $(this).attr("id");
if (tid === rid) {
var date_1 = $(this).val();
ids += rid + ",";
date1 += date_1 + ",";
}
});
};
});
};
<tr id="home">
<td><input class="id" type="checkbox" id=#item.R_ID/></td>
<td>#Html.DisplayFor(x => item.R_ID)</td>
<td><input class="date1" id=#item.R_ID type="text" value='#(item.Date1 == null ? "" : Convert.ToDateTime(item.Date1).ToString("MM/dd/yyy"))' readonly="readonly" /></td>
<td><input class="date2" id=#item.R_ID type="text" value='#(item.Date2 == null ? "" : Convert.ToDateTime(item.Date2).ToString("MM/dd/yyy"))' readonly="readonly" /></td>
</tr>
1) What is your ORM? Entity Framework?
2) Try to debug line:
Hello item = new Hello { R_ID = IDS[i], Date_Two = DateTime.Parse(Date2S[i]), Date_One = DateTime.Parse(Date1S[i]) };
3) Isn't datetime conversion twice there?
First Hello item = ... line, second there
cd.PlanDate = Convert.ToDateTime(item.Date_Two);
cd.PlanDate = Convert.ToDateTime(item.Date_One);
4) What will do the change:
cd.PlanDate = item.Date_Two;
cd.PlanDate = item.Date_One;
?
5) Isn't also a logical fault there to have assignation of 2 values to one variable here?
6) Do you have any javascript extension to your fields on side of Razor template? What format it will produce here if you will pick your time from calendar? Does it fits to your definition mask in model class? (
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
)
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>");
}
}
}
}
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
);
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);
}
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