Not able to load the Gridview on Load - javascript

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>");
}
}
}
}

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();
}
}

how to download excel file for client machine?

1.Input type button show to client-side and click on this button, call the javascript method.
<input type="button" id="btnImportExcel" name="btnImportExcel" value="Export to Excel" class="btn btn-default" onclick="Export_Excel();" style="width: 10%" />
This javascript method retrieves the following parameters value and passes to the code behind web method.
function Export_Excel() {
debugger;
var Showdata = {};
Showdata.startdate = $("[id*=txtbegindate]").val();
Showdata.enddate = $("[id*=txtenddate]").val();
if ($('input[id*=RadioButton1]').is(":checked")) {
Showdata.radio = 1;
}
else if ($('input[id*=RadioButton2]').is(":checked")) {
Showdata.radio = 2;
}
$('#divProgress').show();
$.ajax({
type: "POST",
url: "Agent_HomePage.aspx/efgh",
data: '{xyz: ' + JSON.stringify(Showdata) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
error: function (response) {
alert("Error");
}
});
$('#divProgress').hide();
$('div#OuterShowImageEdu').on('dialogclose', function (event) {
alert('closed');
});
}
we create a web method and using the class object retrieve all parameters values and call the WCF service and pass parameters value.
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public static string efgh(Showdata xyz)
{
string result = "";
DataTable dt;
DataSet ds = new DataSet();
string filename = string.Empty;
try
{
string Sdate = string.Format("{0:dd-MMM-yyyy}", xyz.startdate);
string Edate = string.Format("{0:dd-MMM-yyyy}", xyz.enddate);
List<object> listfinal = new List<object>();
HelloServiceClient client = new HelloServiceClient();
string date = DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss");
var path = Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory);
if (xyz.radio == "1")
{
dt = client.OracleConert_Excel(Convert.ToDateTime(Sdate), Convert.ToDateTime(Edate), dec_cod, 1);
filename = path + "\\Carrier_House_Manifest" + "_" + date + ".xls";
ExporttoExcel(dt, filename);
}
else { }
}
catch (Exception ex)
{ result = ex.Message; }
return result;
}
After WCF services execute successfully and return the result then result convert to excel file.
private static void ExporttoExcel(DataTable dt, string fileName)
{
int i = 0;
int j = 0;
string data = null;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (int i1 = 0; i1 < dt.Columns.Count; i1++)
{
xlWorkSheet.Cells[1, i1 + 1] = dt.Columns[i1].ColumnName;
xlWorkSheet.get_Range("A1", "AA1").Font.Bold = true;
xlWorkSheet.get_Range("A1", "AA1").ColumnWidth = "22";
xlWorkSheet.get_Range("A1", "AA1").Borders.Weight = 4d;
//xlWorkSheet.get_Range("A1", "AA1").Interior.Color = Excel.XlRgbColor.rgbLightSteelBlue;
}
for (i = 0; i <= dt.Rows.Count - 1; i++)
{
int s = i + 1;
for (j = 0; j <= dt.Columns.Count - 1; j++)
{
data = dt.Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[s + 1, j + 1] = data;
}
}
xlWorkBook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
Issue :
I am getting problem file download a client machine.I am trying to file download in client machine but file download on the server.Also, the same code is proper working in my local environment.
You can use SheetJS js-xlsx
Use generateAndDownloadXLSX to download excel file in your page.

C# in javascript executes only once

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
);

Parse string to object

i have created a table in javascript :
var global = [];
function GetValues() {
debugger;
var myList = $("#multiSelect");
var yy = $("#article").val();
var Selectedelement = $("#quantiCommande").val();
myList.append('<option value=' + Selectedelement + '>' + Selectedelement + " " + yy + '</option>');
global.push({ "id": yy, "qte": Selectedelement });
}
i want now to send table global to the controller and this the code of method javasript that send table glabal to the controller:
and this is the form of my table in javascript:enter image description here
function Test() {
var NumCommande = $("#NumCommande").val();
var client = $("#clientc").val();
debugger;
$.ajax({
url: "/Commande/Ajoutercommande?NumCommande=" + NumCommande + "&client=" + client + "&global=" + global, // /Controlleur/Action
type: "POST",
dataType: 'text',
//data : {Nom: nom},
success: function (responseText) {
debugger;
if (responseText == "True") {
alert("Succes");
}
else {
alert("error");
}
}
});
}
and this is my controller methode i need to display the element of my table global
public Boolean Ajoutercommande(string NumCommande, int client, Object global)
{
CRUDEntities db = new CRUDEntities();
Commande c = new Commande();
c.NumCommande = NumCommande;
c.Quantité = client;
Console.Write(global);
db.Commande.Add(c);
db.SaveChanges();
return true;
return true;
}
can someone help me to fix this code and thank you.
I would recommend to create one single object parameter.
Define your datacontract
public class TableContent
{
public int id { get; set; }
public string qte { get; set; }
}
public class AjourtercommandParam
{
public string NumCommande { get; set; }
public int client { get; set; }
public TableContent[] global { get; set; }
}
then, in your controller (WebApi controller, right?)
[HttpPost]
[Route("Commande/Ajoutercommande")]
public async Task<IHttpActionResult> Ajoutercommand(AjoutercommandParam param)
{
if(ModelState.IsValid == false)
{
return BadRequest(ModelState);
}
try
{
var result = await DataLayerService.AjouterCommand(param);
return Ok(result);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
Post your data in the data section of the ajax call.
$.ajax({
url: "/Commande/Ajoutercommande",
type: "POST",
dataType: 'json',
data : {
"NumCommande": NummCommande,
"client" : client,
"global" : global
},
success: function (responseText) {
debugger;
if (responseText == "True") {
alert("Succes");
}
else {
alert("error");
}
}
});

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