error when updating records in web api. - javascript

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.

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

DropDownList with java script

I hope developers can support me, I have minimal experience in the use of java script.
After investigating and several attempts, I was able to load a dropdownlist with data from a LINQ query and pass as a parameter the value of a textbox.
What I could not do is from the query Linq get two fields (Id and value) send them to the dropdownlist and show the value but after being able to use the Id of that field to be able to use it in a create, currently I can only show the value but I need the Id too.
View
#Html.TextBox("CP", "", new { #id = "txtCP", #onchange = "FillOption();", #placeholder = "Codigo Postal" })
#Html.DropDownList("Asentamientos", ViewBag.Drop as List<SelectListItem>)
Script
<script>
function FillOption() {
var CP = $('#txtCP').val();
$.ajax({
type: "Post",
url: "/Home/GetAsentamiento",
data: { CP: CP },
dataType: 'json',
success: function (data) {
$("#Asentamientos").empty();
for (var i = 0; i < data.length; i++) {
$('#Asentamientos').append('<option value=' + data[i].Value + '>' + data[i].Text + '</option > ');
}
}
});
}
</script>
Controllers
public ActionResult Index()
{
List<SelectListItem> drop = new List<SelectListItem>
{
};
ViewBag.Drop = drop;
return View();
}
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select p.Asentamiento).ToList();
SelectList lista = new SelectList(drop2);
ViewBag.lista = lista;
return Json(ViewBag.lista);
}
I think of something like
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { p.IdCodigoPostal,p.Asentamiento}).ToList();
SelectList lista = new SelectList(drop2);
ViewBag.lista = lista;
return Json(ViewBag.lista);
}
but I do not know how the id and the value would be handled
Thanks
If I understand your question correctly, I think you need to name the fields of the object you are creating with the Linq expression, so that it would look something like this:
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { id = p.IdCodigoPostal, value = p.Asentamiento}).ToList();
SelectList lista = new SelectList(drop2);
ViewBag.lista = lista;
return Json(ViewBag.lista);
}
Here are a few examples: https://code.msdn.microsoft.com/LINQ-to-DataSets-09787825#SelectAnonymousTypes1
Then you could access those fields from you javascript with data[i].id and data[i].value.
I hope this helps.
I suspect your issue is around pulling the data from the API result. You're setting the a new property in the ViewBag, then returning the ViewBag property. This really shouldn't be required, and you should instead just return your list, list so (Note: and SelectItemList has a property called "Items" which contains all items you've added):
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { p.IdCodigoPostal,p.Asentamiento}).ToList();
SelectList lista = new SelectList(drop2);
return Json(lista.Items);
}
This should return just a nice list of ListItems. You could also just change your jQuery to loop through the items property, like so:
<script>
function FillOption() {
var CP = $('#txtCP').val();
$.ajax({
type: "Post",
url: "/Home/GetAsentamiento",
data: { CP: CP },
dataType: 'json',
success: function (data) {
$("#Asentamientos").empty();
for (var i = 0; i < data.Items.length; i++) {
$('#Asentamientos').append('<option value=' + data.Items[i].Value + '>' + data.Items[i].Text + '</option > ');
}
}
});
}
</script>
Thanks to all, the code works as follows
Controller
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { Value = p.IdCodigoPostal, Text= p.Asentamiento }).ToList();
SelectList lista = new SelectList(drop2);
return Json(lista.Items);
}
Script
<script>
function FillOption() {
var CP = $('#txtCP').val();
$.ajax({
type: "Post",
url: "/Home/GetAsentamiento",
data: { CP: CP },
dataType: 'json',
success: function (data) {
$("#Asentamientos").empty();
for (var i = 0; i < data.length; i++) {
$('#Asentamientos').append('<option value=' + data[i].Value + '>' + data[i].Text + '</option > ');
}
}
});
}

Post JSON data from JSP using Javascript, AJAX

I want to post JSON data from JSP to Spring MVC Controller. For this, I am using Javascript Ajax. Please help me on this. I searched on net but could not get the solution for my problem.
When I execute the code I get bellow error:
Parse Error: Incorrect syntax Error Unexpected End of Inputand some Ids get printed in a console as below:person#35fcfbc0, person#35fcfbc5`
But I want the value of data1, data2 and data3 to be printed in console;
My Json String as below
{“persons”:
[
{“data1”:”1000”, “data2”:”false”,”data3”:”Holiday”},
{“data1”:”1000”, “data2”:”false”,”data3”:”Holiday”}
]
}
I am using below Javascript and Ajax to post Data
<script type="text/javascript">
$(document).ready(function()
{
var sJson
var ssJson
function dataRow(value1,value2,value3)
{
this.data1 = value1;
this.data2 = value2;
this.data3 = value3;
}
$('#help_button2').click(function()
{
// create array to hold your data
var dataArray = new Array();
var Vars
// iterate through rows of table
// * Start from '2' to skip the header row *
$(".case").each(function(i)
{
if (this.checked)
{
var Vars=i+1
//alert("Checkbox at index " + Vars + " is checked.");
var Vars1= $("#myTable tr:nth-child(" + Vars + ") td").eq(18).find('select').val()
//alert(Vars1)
//alert(Vars)
if (Vars1!="nooption")
{
dataArray.push
(
new dataRow
(
$("#myTable tr:nth-child(" + Vars + ") td").eq(1).html(),
$("#myTable tr:nth-child(" + Vars + ") td").eq(18).find('select').val(),
$("#myTable tr:nth-child(" + Vars + ") td").eq(19).find('select').val()
)
);
} //else {alert("Please Select Option for Error_NoError ")
//return false;
//}
}
});
ssJson1 = JSON.stringify({"persons" : dataArray });
alert(ssJson)
alert(ssJson1)
$.ajax({
url:'<%=webUrl%>/data/data',
type: 'POST',
dataType: 'json',
data:ssJson1,
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
alert(data.data1 + " " + data.data2 + " " + data.data3);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er+ssJson);
}
});
});
});
</script>
My Pojo Class
public class Person implements Serializable{
private int data1;
private String data2;
private String data3;
public int getData1() {
return data1;
}
public void setData1(int data1) {
this.data1 = data1;
}
public String getData2() {
return data2;
}
public void setData2(String data2) {
this.data2 = data2;
}
public String getData3() {
return data3;
}
public void setData3(String data3) {
this.data3 = data3;
}
My Controller code:
#RequestMapping(value="/data",method=RequestMethod.POST)
public #ResponseBody void data(#RequestBody PersonList persons) throws
ParseException, IOException
{
List<Person> data1s=persons.getPersons();
System.out.println(data1s);
}

Input array is longer

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

Categories