var jsonAdim = [];
function openModal(index) {
$("#<%= hidInputSenaryoIndex.ClientID %>").val(index);
$("#senaryoAdimTable tbody").html("");
jsonAdim = $("#<%= hidInputSenaryoAdim.ClientID %>").val();
console.log(jsonAdim);
for (i = 0; i < jsonAdim.length; i++) {
console.log(jsonAdim[i]["Index"] + " -- " + index);
if (jsonAdim[i]["Index"] == index + "") {
var tr = "<tr><td>" + jsonAdim[i]["X"] + "</td><td>" + jsonAdim[i]["Y"] + "</td></tr>";
$("#senaryoAdimTable tbody").append(tr);
}
}
}
I get this to console >
[{"Index":"1","X":"0","Y":"a1"},{"Index":"1","X":"0","Y":"a2"}]
undefined -- 1
Question >
how can I reach this as json? > jsonAdim[i]["Index"]
Looks like what contained in jsonAdim is JSON string, try using JSON.parse to get the objects out the string as follows:
jsonAdimParsed = JSON.parse(jsonAdim);
check out how to use JSON.parse here
Related
I'm working on a bit of code for school but I keep getting an ArgumentOutOfRangeException
With this code I'm trying to read some data from a .csv file and if it equals the name of the image I want it to remove it from the .csv file whilst keeping the structure intact.
public void checkPair(Image card1, Image card2)
{
this.Image1 = card1;
this.Image2 = card2;
if (Convert.ToString(card1.Source) == Convert.ToString(card2.Source) && (card1 != card2))
{
getPoint(card1, card2);
string path = #"Save1.csv";
var reader = new StreamReader(File.OpenRead(path));
var data = new List<List<string>>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';');
data.Add(new List<String> { values[0], values[1]
});
}
reader.Close();
string delimiter = ";";
for (int i = 1; i < 5; i++)
{
for (int x = 0; x < 4; x++)
{
if (data[i][x] == Convert.ToString(card1.Source))
{
data[i][x] = null;
}
}
}
File.WriteAllText(path, data[0][0] + delimiter + data[0][1] + Environment.NewLine + data[1][0] + delimiter + data[1][1] + delimiter + data[1][2] + delimiter + data[1][3] + Environment.NewLine + data[2][0] + delimiter + data[2][1] + delimiter + data[2][2] + delimiter + data[2][3] + Environment.NewLine + data[3][0] + delimiter + data[3][1] + delimiter + data[3][2] + delimiter + data[3][3] + Environment.NewLine + data[4][0] + delimiter + data[4][1] + delimiter + data[4][2] + delimiter + data[4][3] + Environment.NewLine + "ready");
I have no idea why I get this error and how to fix it
Initially, I'd change your last line from
File.WriteAllText(path, data[0][0] + delimiter + data[0][1] ....
to something like
var obj1 = data[0][0];
var obj2 = data[0][1];
File.WriteAllText(path, obj1 + delimiter + obj2 .... etc)
If you over inline functions or array accessing, when you get an exception the stack trace won't be that helpful. At least you'll have an idea of the statement that caused the issue.
This technique can prove to be very helpful, if you are looking at an in exception in the logs, after the fact.
My coding are as following.
I cannot get the selected value of AreaDetails_code dropdownlist selected value.
I got the null value only. Pls help me. Thanks in advance.
In my Create.cshtml
<div id="hsp-planner"></div>
<script type="text/javascript">
$('#butGenerate').click(`function generateTimeLine() {
$('#hsp-planner').html('');
var _location = $('#pAreaInfoId').val();
var _staff = $('#pStaff').val();
var _selVal = $('#AreaDetails_code').val();
$.ajax({
url: '#Url.Action("GetAjaxPlanner", "HourlyShiftPlanner")',
data: { location: _location, staff: _staff, selectval: _selVal },
//dataType: 'json',
success: function (data) {
$('#hsp-planner').html(data);
},
failure: function (response) {
alert(response);
}
});
});
});
`
</script>
In my Controller.cs
public string GetAjaxPlanner()
{
string locationId = Request.QueryString["location"];
string staffId = Request.QueryString["staff"];
string selectVal = Request.QueryString["selectval"];
//String str = (String)req.getParameter("AreaDetails_code");
if (locationId != null && locationId != "")
{
List<ShiftAllocation> saList = new ShiftAllocationRepository().FindByAreaInfoId(int.Parse(locationId));
if (saList.Count > 0)
{
string result = "";
result = "<table>";
result += "<tr>";
result += "<td>Time Period<br/>(From-To)</td>";
result += "<td>Duty Location</td>";
//result += "<td>Remark</td>";
result += "<td>Staff</td>";
result += "</tr>";
int i = 1;
foreach (ShiftAllocation sa in saList)
{
HourlyShiftPlanner objHsp = null;
string dutyLocation = "";
string remark = "";
if (staffId != null && staffId != "")
{
objHsp = new HourlyShiftPlannerRepository().FindStaff(int.Parse(staffId), int.Parse(locationId), sa.ShiftAllocationId);
}
if (objHsp != null)
{
dutyLocation = objHsp.DutyLocation;
remark = objHsp.Remark;
}
result += "<tr>";
result += "<td>" + sa.FromShift.ToString("HH:mm") + "-" + sa.ToShift.ToString("HH:mm") + "</td>";
result += "<td>" + this.GetLocDetailsListWithDDL(i) + "</td>";
result += "</tr>";
result += "<input type='hidden' name='hidSAId" + i + "' id='hid-sa-id" + i + "' value='" + sa.ShiftAllocationId + "'/>";
i++;
}
result += "</table>";
return result;
}
}
return null;
}
private string GetLocDetailsListWithDDL(int idx2)
{
List<AreaInfoDetails> _areaDetailsList = db.AreaInfosDetails.ToList();
if (_areaDetailsList.Count == 0) return "";
string result = "";
result = "<select name='AreaDetails_code" + idx2 + "' id='AreaDetails_code" + idx2 + "'>";
result += "<option value=>--Select item--</option>";
foreach (AreaInfoDetails _ad in _areaDetailsList)
{
result += "<option value='" + _ad.AreaInfoDetailsId + "'>" + _ad.AreaDetailsCode + " </>";
}
result += "</select>";
//result += "<input type=submit id=submit value=Submit </>";
return result;
}`
In your controller you have this line:
result = "<select name='AreaDetails_code" + idx2 + "' id='AreaDetails_code" + idx2 + "'>";
where idx2 is a variable int, when you're trying to obtain the value with jquery:
var _selVal = $('#AreaDetails_code').val();
you are not appending this idx2 value in the selector and thus jquery assigns the value of null because it can't find it.
If you delete this placeholder from your controller, then you'll end up with multiple elements with the same id...no bueno. You must find a better naming convention or somehow pass that value to your view/javascript so it can know which element to get the value of.
Hope that helps.
NOW SOLVED
Hi I am calling a c# web method via Ajax.
I want to handle a returned value of true and false in Ajax but I cannot seem to find a way of interrogating my returned data.
Sorry if this is a easy question, I am quite the novice.
My code is
$.ajax({
url: "Subscriptions.aspx/AddSub",
data: "{ 'strReportPath': '" + Path +
"' , strEmail: '" + $('#EmailAddress').val() +
"' , strDayofWeek: '" + daysSelected +
"' , strInterval: '" + intervalSelected +
"' , intTimeofDay: '" + timeofDay +
"' , strDayofMonth: '" + dayofMonth +
"'}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data[0] == true) {
alert("Subscription added");
} else {
alert("There has been a error");
}
// Enable button again
$(".AddSub").removeAttr("disabled");
},
error: function (xhr, status, err) {
alert("Error adding subscription: " + err);
// Enable button again
$(".AddSub").removeAttr("disabled");
},
async: false
});
and the web method is
[WebMethod]
public static bool AddSub(string strReportPath, string strEmail, string strDayofWeek, string strInterval, int intTimeofDay, int strDayofMonth)
{
// Create webservice object
ReportService2005.ReportingService2005 rs = new ReportingService2005();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
try
{
// Make sure their is a semi colon at the end of the email
if (strEmail.EndsWith(";"))
{
// Do nothing
}
else
{
strEmail = strEmail + ";";
}
string _reportName = strReportPath;
DateTime topDatetime = DateTime.Now;
ExtensionSettings extensionSettings = new ExtensionSettings();
List<ParameterValue> extParameters = new List<ParameterValue>();
List<ParameterValue> parameters = new List<ParameterValue>();
string description = "Email: " + strEmail;
string eventType = "TimedSubscription";
extensionSettings.Extension = "Report Server Email";
// If report is monthly default its run time to 7am
if (strInterval == "Monthly")
{
intTimeofDay = 7;
}
string scheduleXml = "<ScheduleDefinition><StartDateTime>" + topDatetime.ToString("yyyy-MM-dd") + "-" + (intTimeofDay-1) +":00" + "</StartDateTime>";
// Set up the timing of the report.
switch(strInterval)
{
case "Daily":
scheduleXml += "<WeeklyRecurrence>" +
"<WeeksInterval> 1 </WeeksInterval>" +
"<DaysOfWeek>" + "<Monday>true</Monday>" +
"<Tuesday>true</Tuesday>" +
"<Wednesday>true</Wednesday>" +
"<Thursday>true</Thursday>" +
"<Friday>true</Friday>" + "</DaysOfWeek>" +
"</WeeklyRecurrence>";
break;
case "Weekly":
scheduleXml += "<WeeklyRecurrence>" +
"<WeeksInterval> 1 </WeeksInterval>" +
"<DaysOfWeek>" + strDayofWeek + "</DaysOfWeek>" +
"</WeeklyRecurrence>";
break;
case "Monthly":
scheduleXml += "<MonthlyRecurrence>" +
"<Days>" + strDayofMonth + "</Days>" +
"<MonthsOfYear>" +
"<January>true</January>" +
"<February>true</February>" +
"<March>true</March>" +
"<April>true</April>" +
"<May>true</May>" +
"<June>true</June>" +
"<July>true</July>" +
"<August>true</August>" +
"<September>true</September>" +
"<October>true</October>" +
"<November>true</November>" +
"<December>true</December>" +
"</MonthsOfYear>" +
"</MonthlyRecurrence>";
break;
}
scheduleXml += "</ScheduleDefinition>";
extParameters.Add(new ParameterValue() { Name = "RenderFormat", Value = "EXCELOPENXML" });
extParameters.Add(new ParameterValue() { Name = "TO", Value = strEmail });
extParameters.Add(new ParameterValue() { Name = "IncludeReport", Value = "True" });
extParameters.Add(new ParameterValue() { Name = "Subject", Value = "subject - " + " (" + strReportPath + ")" });
extensionSettings.ParameterValues = extParameters.ToArray();
//Create the subscription
rs.CreateSubscription(_reportName, extensionSettings, description, eventType, scheduleXml, parameters.ToArray());
// Success
return true;
}
catch(SoapException e)
{
// Failure
return false;
}
}
Thank you
ANSWER
Ah solved it!!!
I now return the data as a string variable in the web method
//Create the subscription
rs.CreateSubscription(_reportName, extensionSettings, description, eventType, scheduleXml, parameters.ToArray());
string bob = "true";
// Success
return bob;
}
catch(SoapException e)
{
string bob = "false";
// Failure
return bob;
}
Then in ajax use the name followed by the .d suffix.
success: function (bob) {
if (bob.d == "true") {
alert("Subscription added");
} else {
alert("There has been a error");
}
Thanks stackoverflow
I want to make a multiple upload, iam using some script from this forum.
the scripts is perfectly works, but when i merge it with my project.
javascript can't get the value of my element.
i found out the problem is because i have many ID PANEL in the page, i need to change to getElementByID('<%="FileUpdate.ClientID%>').value (the original : getElementByID("FileUpdate").value)
THE PROBLEM IS :
I have to use counter, ex: getElementByID('<%="txtFileUpdate' + counter + '%>').value but it FAIL.
the error says "too many characters in character literal" pointing to that line.
Please someone help, is there any solution for this problem ?
Here is the script
-----> Error " to many characters in character literal"
<script type="text/javascript" language="javascript">
var counter = 1;
function AddFileUpload() {
if (counter < 5) {
counter++;
var div = document.createElement('DIV');
div.innerHTML = '<input id="FileUpload' + counter + '" name = "file' + counter +
'" type="file" />' +
'<input id="Button' + counter + '" type="button" ' +
'value="Remove" onclick = "RemoveFileUpload(this)" />';
document.getElementById("FileUploadContainers").appendChild(div);
}
else {
alert("Cannot attach more than 5 file");
}
}
function GetFile() {
var temp;
var error = "";
var stringx = "";
var exCounter = 1 ;
for (exCounter; exCounter <= counter; exCounter++) {
-----> stringx = document.getElementById('<%=FileUpload'+exCounter+'.ClientID%>').value;
if (stringx != "")
temp += stringx + "#;";
else
error += exCounter + ", ";
}
if (error != "") {
alert("Field " + error + " Still Empty");
return;
}
document.getElementById('<%=HiddenField1.ClientID%>').value = temp;
}
Try this:
getElementByID('FileUpdate<%=counter%>').value
or
getElementByID('<%=txtFileUpdate + counter.ToString()%>').value
This is my code:
webBrowser1.ObjectForScripting = this;
string str =
"<html><head><script type=\"text/javascript\">" +
"var list = document.getElementsByTagName('abbr');" +
"len = list.length;" +
"for(i = 0;i < len;i++)" +
"{obj=list[i];obj.onclick=window.external.Test(this.id);}" +
"</script></head>" +
"<body>";
for (int i = 1000; i < 1100; i++)
{
str += "<abbr id=\'" + i.ToString() + "\'" +
">" + i.ToString() + " </abbr>";
}
str += "</body></html>";
webBrowser1.DocumentText = str;
Thanks
As you placed your script in the <head>, it gets executed before the contents of the <body> are fully loaded. There are two possibilities to avoid that problem: You could place the script before the ending </body>-Tag or you execute your script onload.
window.onload = function () {
// Insert code that depends on a loaded body here.
}