Input array is longer - javascript

I try to display data in grid view through web method and jquery function so i try this. I try to display gridview when user select value from drop-down and select dates from calendar
$(function () {
$('[ID*=search_data]').on('click', function () {
var fromdate = $('[ID*=fromdate]').val();
var todate = $('[ID*=todate]').val();
var regiondrop = $('[ID*=regiondrop] option:selected')[0].value;
var GridView1 = $('[ID*=GridView1]');
var obj = {};
obj.fromdate = fromdate;
obj.todate = todate;
obj.regiondrop = regiondrop;
Getdataa(obj);
});
});
function Getdataa(obj) {
//alert('1');
$.ajax({
type: "POST",
url: "WebForm1.aspx/search_data",
data: "{'fromdate':'" + obj.fromdate + "','todate':'" + obj.todate + "','regiondrop':'" + obj.regiondrop + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
$("#GridView1").empty();
if (result.d.length > 0) {
$("#GridView1").append(
"<tr><th>ID</th><th>OName</th><th>Reg No</th><th>Speed</th></tr>");
for (var i = 0; i < result.d.length; i++) {
$("#GridView1").append("<tr><td>" +
result.d[i].ID+ "</td> <td>" +
result.d[i].OName + "</td> <td>" +
result.d[i].Reg No+ "</td> <td>" +
result.d[i].Speed+ "</td></tr>");
}
}
else {
$("#GridView1").hide();
$("#Label1").text("No Data");
}
},
error: function (error) {
alert("error");
}
});
}
WebMethod
[WebMethod]
public static DataTable search_data(DateTime fromdate, DateTime todate, string regiondrop)
{
try
{
T1 ts = new T1();
var dq = (from vv in ts.tblVe
join rv in ts.tblRe on vv.ID equals rv.ID
join re in ts.tblReg on rv.RID equals re.RID
where
re.Region == regiondrop
&& re.StartDate <= fromdate
&& re.EndDate >= todate
orderby
vv.ID,
rv.OwnerName
select new
{
ID=rv.ID,
OName = rv.OName ,
RegNo = rv.RegNo,
Speed = rv.Speed ,
}).ToList();
DataTable dt = new DataTable();
dt.Rows.Add(dq);
return dt;
}
catch (Exception)
{
throw new Exception();
}
}
in var dq.. dq show this data
[0] = { ID = 1, OName = "Khan", RegNo = "AJ-24",Speed = "124" } [1] = { ID = 2, OName = "Shah", RegNo = "AL-91",Speed = "95" }
UPDATE
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("OName", typeof(string));
dt.Columns.Add("RegNo", typeof(string));
dt.Columns.Add("Speed", typeof(string));
dt.Rows.Add(dq);
return dt;
and exception occur
Unable to cast object of type 'System.Collections.Generic.List`1[<>f__AnonymousType6`5[System.Int32,System.String,System.String,System.String,System.String]]' to type 'System.IConvertible'.Couldn't store <System.Collections.Generic.List`1[<>f__AnonymousType6`5[System.Int32,System.String,System.String,System.String,System.String]]> in ID Column.

You will have to add the columns in you datatable
dt.Columns.Add();
for more information : https://msdn.microsoft.com/en-us/library/hfx3s9wd(v=vs.110).aspx

Related

JSTree - why is it not reading from my JSON Array correctly but renders properly when returned a single JSON string?

I've been working on this for days and can't see to crack it! Deadlines are very close and I am full of covid. Please please help me crack it asap. I feel like i've tried every option of square brackets, curly brackets but I just can't get JSTree to interpret it correctly from my Array. When I return a 1 line string using the exact same format, JSTree correctly renders it as a folder with the correct name but when I return the Array, JSTree shows a list of folders but they have the whole string as the name:
https://i.imgur.com/A0U9gGi.png
I've checked the JSON Array using this checker: https://jsonformatter.curiousconcept.com/
and it checks properly:
Returned Array:
[{"id":"New Lib","parent":"#","text":"New Lib","data":"0"},{"id":"40","parent":"New Lib","text":"Text TXT","data":"1"},{"id":"39","parent":"New Lib","text":"new 5","data":"2"},{"id":"34","parent":"New Lib","text":"Hi","data":"3"},{"id":"41","parent":"34","text":"Test URL Facebook","data":"4"},{"id":"37","parent":"34","text":"Hi 2","data":"5"}]
Output from the checker:
[
{
"id":"New Lib",
"parent":"#",
"text":"New Lib",
"data":"0"
},
{
"id":"40",
"parent":"New Lib",
"text":"Text TXT",
"data":"1"
},
{
"id":"39",
"parent":"New Lib",
"text":"new 5",
"data":"2"
},
{
"id":"34",
"parent":"New Lib",
"text":"Hi",
"data":"3"
},
{
"id":"41",
"parent":"34",
"text":"Test URL Facebook",
"data":"4"
},
{
"id":"37",
"parent":"34",
"text":"Hi 2",
"data":"5"
}
]
Maybe I need to parse it somehow? I've found this thread: Loading Json as variable into jsTree
But I don't understand how to implement this into mine fully
C# Code:
[WebMethod]
public static Array getChildren(string libraryID)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
//Get the library name
string getUserInfo = "select LibraryName from Document_Library_Names where Id =" + libraryID;
SqlCommand getUserInfocmd = new SqlCommand(getUserInfo, con);
string libraryName = Convert.ToString(getUserInfocmd.ExecuteScalar()).Trim();
//Getting documents
string strGetDocuments = "Select * from Documents where LID =" + libraryID + " order by DisplayOrder ASC";
SqlCommand getDocumentsCMD = new SqlCommand(strGetDocuments, con);
getDocumentsCMD.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataReader sqlDR = getDocumentsCMD.ExecuteReader();
dt.Load(sqlDR);
sqlDR.Close();
if (dt != null)
{
if (dt.Rows.Count > 0)
{
int arrayCount = dt.Rows.Count;
int rowCount = 1;
string arrayEnd = "";
string[] documentArray = new string[arrayCount+1];
//List<string> documentList = new List<string>();
documentArray[0] = "[{\"id\":\"" + libraryName + "\",\"parent\":\"#\",\"text\":\"" + libraryName + "\",\"data\":\"0\"}]";
//Build the string
foreach (DataRow row in dt.Rows)
{
//Getting the data
string ID = row[0].ToString().Trim();
string type = row[2].ToString().Trim();
string name = row[3].ToString().Trim();
string parentFolder = row[4].ToString().Trim();
string displayOrder = row[5].ToString().Trim();
string extension = row[8].ToString().Trim();
//Get parentFolder ID
string parentFolderID = "0";
if (parentFolder != "")
{
string strParentFolderID = "Select ID from Documents where Name=#Name and Type=0";
SqlCommand strParentFolderIDcmd = new SqlCommand(strParentFolderID, con);
strParentFolderIDcmd.Parameters.AddWithValue("#Name", parentFolder);
parentFolderID = Convert.ToString(strParentFolderIDcmd.ExecuteScalar());
}
else
{
parentFolderID = libraryName;
}
documentArray[rowCount] = "[{\"id\":\"" + ID + "\",\"parent\":\"" + parentFolderID + "\",\"text\":\"" + name + "\",\"data\":\"" + displayOrder + "\"}]";
rowCount = rowCount + 1;
}
con.Close();
return documentArray;
}
else
{
con.Close();
return null;
}
}
else
{
con.Close();
return null;
}
}
Javascript:
<script type="text/javascript">
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const libraryID = urlParams.get('ID');
$('#libraryTreeview').jstree({
"core": {
"data": {
type: "POST",
url: "LibraryFiles.aspx/getChildren",
data: '{"libraryID":"' + libraryID + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d);
data.d;
$(data).each(function () {
return { "id": this.id };
});
}
},
"themes": {
dots: false,
//"variant": "large",
//"responsive": true
},
"types": {
"FDR": {
"icon": "WebsiteImages/LibraryIcons/Folder48.png"
},
"IMG": {
"icon": "WebsiteImages/LibraryIcons/Image48.png"
}
},
"plugins": ["types", "themes"]
}
});
</script>

Asp.net mvc dropdownlist cascading error Cannot set property 'value' of null

Hy.
I want to make dropdownlist cascadin. select dropdownlist and send editorfor.but
Cannot set property 'value' of null error .
I would like to send a value to editorfor a value of dropdownlist.
Can you help me?
public JsonResult GetPrice(string log)
{
int id = 1;
HomeController.sqlconnection con = new HomeController.sqlconnection();
string FIRMA = "select t.FIRMA,t.donem FROM dbo.TBLFRM as t where t.ID=" + id + "";
SqlCommand cmd = new SqlCommand(FIRMA, con.connect());
SqlDataReader rdrr = cmd.ExecuteReader();
rdrr.Read();
string firma = rdrr["FIRMA"].ToString();
string donem = rdrr["DONEM"].ToString();
ExtreModel item = new ExtreModel();
item.ItemList = new List<ExtreModel>();
string urun = "select P.PRICE from DBO.LG_" + firma + "_PRCLIST as p,DBO.LG_" + firma + "_ITEMS as I WHERE P.CARDREF=I.LOGICALREF AND P.CARDREF=" + log + "";
SqlCommand cmdd = new SqlCommand(urun, con.connect());
SqlDataReader rdr = cmdd.ExecuteReader();
rdr.Read();
string PRICE = rdr[0].ToString();
con.connect().Close();
return Json(PRICE, JsonRequestBehavior.AllowGet);
}
<script>
$("#LOGI").change(function () {
var select = $(this);
var cityname = select.val();
if (cityname != "") {
$.ajax({
method: "GET",
url: '/Mobil/GetPrice' + '?log=' + cityname,
beforeSend: function () {
}
}).done(function (result) {
document.getElementById("fyt").value = result.PRICE;
});
} else {
}
});
</script>
The problem seems coming from this return statement:
return Json(PRICE, JsonRequestBehavior.AllowGet);
This statement returns plain string value which doesn't contain PRICE property, so result.PRICE contains null value and causing null property assignment error message. If you want to return the price value, simply use this inside done function:
document.getElementById("fyt").value = result;
or in jQuery version:
$('#fyt').val(result);
But if you still want to return PRICE property, specify it inside JSON data:
return Json(new { PRICE = PRICE }, JsonRequestBehavior.AllowGet);
And the AJAX callback should be look like this:
$("#LOGI").change(function () {
var cityname = $(this).val();
if (cityname != "") {
$.ajax({
type: "GET",
url: '/Mobil/GetPrice',
data: { log: cityname }
}).done(function (result) {
$("#fyt").val(result.PRICE); // now the price property should exist
});
} else {
// do something else
}
});

ASP.net Textbox Live Search - GridView Results Filter

My scenario is; I'm trying to do a live search feature for my ASP.net project. In the form, I have a description textbox where the user will type in the search and as the user types in anything, the GridView below filters the results accordingly. I have tried this on desktop applications and it's not much of a hassle but I recently dipped in on Web Applications. Any help would be appreciated. I'm sure there is an easy way to do this but I seem to be having trouble finding "that" way.
Below are what I tried already:
I have tried using onTextChanged property of the textbox but it only populates after the event request.
I have added a function using Ajax+ JQuery which calls the method but the gridview is not displaying the data.
enter code here
<script type="text/javascript">
$(function () {
GetCustomers();
});
$("[id*=TxtDescription]").live("keyup", function () {
GetCustomers();
});
function SearchTerm() {
return jQuery.trim($("[id*=TxtDescription]").val());
};
function GetCustomers() {
$.ajax({
type: "POST",
url: "frmDrugMaster.aspx/GetCustomers",
data: '{searchTerm: "' + SearchTerm() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
var row;
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var customers = xml.find("Drugs");
alert(customers.length);
if (row == null) {
row = $("[id*=gvCustomers] tr:last-child").clone(true);
}
$("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
if (customers.length > 0) {
alert(customers.length);
$.each(customers, function () {
var customer = $(this);
$("td", row).eq(0).html($(this).find("DR_Code").text());
$("td", row).eq(1).html($(this).find("DR_Description").text());
$("td", row).eq(2).html($(this).find("DR_UnitDose").text());
alert($("td", row).eq(0).html($(this).find("DR_Description").text()));
$("[id*=gvCustomers]").append(row);
$
row = $("[id*=gvCustomers] tr:last-child").clone(true);
});
} else {
var empty_row = row.clone(true);
$("td:first-child", empty_row).attr("colspan", $("td", row).length);
$("td:first-child", empty_row).attr("align", "center");
$("td:first-child", empty_row).html("No records found for the search criteria.");
$("td", empty_row).not($("td:first-child", empty_row)).remove();
$("[id*=gvCustomers]").append(row);
}
};
</script>
[WebMethod]
public static string GetCustomers(string searchTerm)
{
SqlConnection cn = new SqlConnection(WebConfigurationManager.ConnectionStrings["dbconn"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT a.DR_UNITDOSE, a.DR_CODE, a.DR_DESCRIPTION, a.DR_GENERIC1, a.DR_GENERIC2, a.DR_GENERIC3, a.DR_GENERIC4, a.DR_COSTPRICE, a.DR_SELLPRICE, a.DR_STATUS FROM DRUGMASTER a, DRUGCATEGORY b where a.DR_CATEGORY = b.DC_CODE and DR_DESCRIPTION='"+ searchTerm + "' ", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
DataTable dt = new DataTable();
dt.TableName = "Drugs";
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
DataSet ds = new DataSet();
ds.Tables.Add(dt);
return ds.GetXml();
}
I found a solution to this or atleast a sort to workaround it. I used AJAX + JQuery. I just created a web service for the particular page where the text change will be applied. The codes used are as follows. Hope this helps someone:
/*form*/
create a webform with a textbox and a gridview:
/*Add this script*/
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
script type="text/javascript">
$(function () {
$("[id*=txtCountry]").on("keyup", function () {
$.ajax({
type: "POST",
url: "WebForm2.aspx/GetCustomers",
data: '{searchTerm: "' + $(this).val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var row;
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var customers = xml.find("Customers");
if (row == null) {
row = $("[id*=gvCustomers] tr:last-child").clone(true);
}
$("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
if (customers.length > 0) {
$.each(customers, function () {
$("td", row).eq(0).html($(this).find("PD_FSTNM").text());
$("td", row).eq(1).html($(this).find("PD_GENDER").text());
$("[id*=gvCustomers]").append(row);
row = $("[id*=gvCustomers] tr:last-child").clone(true);
});
} else {
var empty_row = row.clone(true);
$("td:first-child", empty_row).attr("colspan", $("td", row).length);
$("td:first-child", empty_row).attr("align", "center");
$("td:first-child", empty_row).html("No records found for the search criteria.");
$("td", empty_row).not($("td:first-child", empty_row)).remove();
$("[id*=gvCustomers]").append(empty_row);
}
},
failure: function (response) { alert(response.d); },
});
});
});
</script>
/*C# Code*/
[System.Web.Services.WebMethod]
public static string GetCustomers(string searchTerm = "")
{
string strConnString = ConfigurationManager.ConnectionStrings[""].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
string query = "SELECT * FROM patientdetails";
if (!string.IsNullOrEmpty(searchTerm))
{
query += " WHERE PD_FSTNM LIKE '" + searchTerm + "%'";
}
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds, "Customers");
return ds.GetXml();
}

error when updating records in web api.

After selecting the department to update.
a submit button is click.
this error appear
{"readyState":4,"reponseText":"{\"Message\":\"Object reference not set to an instance of an object.\",\"StackTrace\":\" at WebService.yearEndClosing(String strDate, String endDate, String cond, String cal, String entryUser)in WebService.cs:line 390\",\"ExecptionType\":\"System.NullReferenceException\"}","responseJSON":{"Message":"Object reference not set to an instance of an object.","StackTrace":" at WebService.yearEndClosing(String strDate, STring endDate, String cond, String val, String entryUser) in WebService.cs:line 390\",\"ExecptionType\":\"System.NullReferenceException\"},"status":500, "statusText":"Internal Server Error"}
The code for submit button.
//Function for submit button event
$(function () {
$("#btnSubmit").bind("click", function (e) {
if (confirm("Click [OK] to proceed on forfiet the leave of selected department.")) {
var selectedDept = new Array();
var i = 0;
//Get checked checkbox in the list
$(".bodyfont input").each(function () {
if ($(this).is(":checked")) {
selectedDept[i] = $(this).val();
i++;
}
});
var ddlVal = $("[id*='ddlVal']").val();
var endDate = $("[id*='tEnd']").val();
var strDate = $("[id*='tStart']").val();
if (strDate != "" && endDate !="" && i > 0) {
ShowLoading();
$.ajax({
type: "POST",
url: "WebService.asmx/yearEndClosing",
data: "{ 'strDate':'" + strDate + "', 'endDate':'" + endDate +
"', 'cond':'" + ddlVal + "', 'val':'" + JSON.stringify(selectedDept) +
"', 'entryUser':'" + getLoginID() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var json_obj = data.d;//parse JSON
if (json_obj != null) {
if (json_obj.length == 0) {
alert("All selected department/employee in date range are closed!")
}
else {
//deserialize json object to string
var table = "";
$("#tblNotClose tr").remove();
$.each(json_obj, function (index, YrEndClosing) {
table += "<tr><td>" + YrEndClosing.empID + "</td><td>" + YrEndClosing.empName + "</td></tr>";
});
if (table != "") {
header = "<tr><th>Emp ID</th><th>Emp No</th></tr>";
$("#tblNotClose").append(header);
$("#tblNotClose").append(table).removeClass("hidden");
}
$("#modalResult").modal('show');
}
}
else {
alert("Error on closing");
}
ShowDetails();
},
error: function (error) {
alert(JSON.stringify(error));
}
});
e.preventdefault;
}
else {
alert("Due Date is not seleceted to forfiet the leave");
}
}
});
});
And it is this alert(JSON.stringify(error)); which display the error.
Now lets breakdown the issue. base on my understanding
the error is telling that there is something going on with the parameter in
yearEndClosing(String strDate, String endDate, String cond, String cal, String entryUser) which is on line 390
here i the code
[WebMethod(EnableSession = true), ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<YrEndClosing> yearEndClosing(string strDate, string endDate, string cond, string val, string entryUser)
{
eLeaveModule em = new eLeaveModule();
JavaScriptSerializer json = new JavaScriptSerializer();
List<string> arrayString = json.Deserialize<List<string>>(val);
DateTime dtStr = Convert.ToDateTime(strDate, CultureInfo.GetCultureInfo("en-us").DateTimeFormat);
DateTime dtEnd = Convert.ToDateTime(endDate, CultureInfo.GetCultureInfo("en-us").DateTimeFormat);
List<YrEndClosing> result = em.yearEndClosing(dtStr, dtEnd, cond, arrayString, entryUser);
if (result.Count > 0)
{
string relDate = Regex.Replace(string.Format("{0:s}", DateTime.Now), #"[^0-9a-zA-Z]+", "");
string subPath = #" C:\webOutput\eHRMS\Closing\";
bool exists = System.IO.Directory.Exists(subPath);
if (!exists)
System.IO.Directory.CreateDirectory(subPath);
using (StreamWriter writer = new StreamWriter(subPath + "ClosingList" + relDate + ".txt"))
{
for (int i = 0; i < result.Count; i++)
{ writer.WriteLine(result[i].empID + "-" + result[i].empName); }
}
}
return result;
}
USEFUL INFORMATION
The code work in server 2
The same code not working in server 1 (current issue)
No error when running on local by visual studio for web
May i know what could be the issue.
I am still trying to even locate where the possible issue is at.

Binding Kendo Data Source with Async $.ajax calling from C# MVC Controller Action

This is my action in controller. Which return a List> converting into DataSourceResult.and also Serializing into Json.
[HttpPost]
public ActionResult GetMissingShiftData([DataSourceRequest]DataSourceRequest request)
{
DataTable dtResponse = new DataTable();
var dynamicList = new List<dynamic>();
var myMainList = new List<List<dynamic>>();
List<DataSourceResult> viewResultList = new List<DataSourceResult>();
string RigNumber = string.IsNullOrWhiteSpace( resultData.Filter.SelectedRig.RigNumber) || resultData.Filter.SelectedRig.RigNumber == "ALL" ? "" : resultData.Filter.SelectedRig.RigNumber;
DataSet response = MissingShiftsReportData.GetData(Convert.ToDateTime(resultData.Filter.DateStart), Convert.ToDateTime(resultData.Filter.DateEnd), ConnString, RigNumber);
foreach (DataTable dt in response.Tables)
{
dtResponse = dt;
string[] columnNames = dtResponse.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
foreach (DataRow dr in dtResponse.Rows)
{
dynamic myObj = new ExpandoObject();
var p = myObj as IDictionary<string, object>;
Regex rgx = new Regex("[^a-zA-Z0-9]");
for (int i = 0; i < columnNames.Length; i++)
{
string name = dr.Table.Columns[i].ColumnName.Replace(" ", String.Empty);
name = name.Replace(".", String.Empty);
name = name.Replace("(", String.Empty);
name = name.Replace(")", String.Empty);
name = rgx.Replace(name, "");
p[name] = dr[i];
}
dynamicList.Add(p);
}
myMainList.Add(dynamicList);
}
DataSourceResult viewResult = myMainList.ToDataSourceResult(request);
string JsonViewData = JsonConvert.SerializeObject(viewResult.Data);
return new ContentResult { Content = JsonViewData, ContentType = "application/json", ContentEncoding = Encoding.UTF8 };
}
And this is the async call I am doing with Jqery.while I am trying to bind a data source it shows "data[0].Data" is "undefined". How can I make use of 'data'.
$.ajax({
url: "GetMissingShiftData",
type: "post",
datatype: 'json',
success: function (data) {
var list = data[0].Data;
var dataSource = new kendo.data.DataSource({
data: data[0].Data
});
dataSource.read();
return false;
},
error: function (msg) {
toastr.error("Error: " + msg.statusText);
}
});
You are serializing an array (the Data property) and don't need to use the Data field at the client-side:
$.ajax({
url: "GetMissingShiftData",
type: "post",
datatype: 'json',
success: function (data) {
var dataSource = new kendo.data.DataSource({
data: data
});
dataSource.read();
return false;
},
error: function (msg) {
toastr.error("Error: " + msg.statusText);
}
});

Categories