Populating a hiddenfield with a delimeter. _delimiter not declared - javascript

I am trying to populate a hidden field with the values that are added to my list box. I am getting the message _delimiter is not declared. So the hidden field value would be 123456,651456,654321 etc..
<script language="javascript" type="text/javascript">
function getSelected(source, eventArgs) {
var s = $get("<%=NameTextBox.ClientID %>").value;
var opt = document.createElement("option");
opt.text = s.substring(s.length - 10);
opt.value = s.substring(s.length - 10);
document.getElementById('<%= Listbox.ClientID %>').options.add(opt);
$hidlistbox = $('#<%= hidListBox.ClientID %>');
$textbox = $('#<%= NameTextBox.ClientID %>');
$hidlistbox.val($hidlistbox.val() + $textbox.val() + '<%= _delimiter %>');
$textbox.val('');
}
Private Sub PopulateListBox()
Dim _delimiter As Char = ","c
If NameTextBox.Text = "" Then
Else
' Get value from text box
Dim textBoxValue As String = Me.NameTextBox.Text
' Create new item to add to list box
Dim newItem As New ListItem(textBoxValue)
' Add item to list box and set selected index
Listbox.Items.Add(newItem)
Listbox.SelectedIndex = Listbox.Items.Count - 1
hidListBox.Value = _delimiter.ToString
End If
End Sub

In your javascript, you are trying to evaluate the server side _delimiter variable, which seems to be private to the PopulateListBox method.
You should either define a public _delimiter property in your code behind, or double check if you really need its evaluation in the javascript.

Related

In ASP with VB codebehind how do I present the user a yes/no dialog from VB

I have the following case where a user has selected a product, the product record has been retrieved and the backorder flag is set. I want to ask the user if the want to include it in the order anyway. I can't seem to find an exaample anywhere that demonstrates it in an IF statement.
My VB Code Snippet:
Dim backorder = myDataTable.Rows(0)("backorder").ToString()
If backorder = "True" And <somehow ask user it they want to order anyway> Then
'do something
End If
My Javascript in aspx file:
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Selected item is on temporary back order. Do yuou want to include it on this order?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
I can read the variable being added, by javascript, to the page from VB, but can't figure how to call the javascript in order to prompt the user.
For some reason I can't get my head around this. Please advise with example.
Use the RegisterStartupScript method:
Sub ProcessOrder()
'Your code to process the selected products here...
Dim orderAnyway As string = hdnConfirmResponse.Value.Trim()
If selectedItem.BackOrdered Then
If orderAnyway = "" Then
Dim cs As ClientScriptManager = Page.ClientScript
' Define the name and type of the client scripts on the page.
Dim csname1 As String = "ConfirmScript"
Dim cstype As Type = Me.GetType()
' Check to see if the startup script is already registered.
If (Not cs.IsStartupScriptRegistered(cstype, csname1)) Then
Dim cstext1 As String = "Confirm();"
cs.RegisterStartupScript(cstype, csname1, cstext1, True)
End If
Else
If orderAnyway = "yes" Then
'ADD THE BACKORDERED ITEM SINCE THEY CONFIRMED
End If
End If
End If
End Sub
I hate answering my own question but this what finally worked. Mixture of mjw's answer and more research on my javasvript attempt. Rather than have JS create the hidden field, I added it to the HTML
<asp:HiddenField runat="server" id ="confirm_value"/>
New VB:
If myDataTableFrame.Rows.Count > 0 Then
Dim backorder = myDataTableFrame.Rows(0)("backorder").ToString()
If backorder = "True" And confirm_value.Value <> "Yes" Then
Dim cs As ClientScriptManager = Page.ClientScript
' Check to see if the startup script is already registered.
If (Not cs.IsStartupScriptRegistered(Me.GetType(), "ConfirmScript")) Then
Dim cstext1 As String = "Confirm();"
cs.RegisterStartupScript(Me.GetType(), "ConfirmScript", "Confirm();", True)
End If
Return
Else
confirm_value.Value = "No"
...
New Javascript:
See ASP.NET set hiddenfield a value in Javascript Also added a reclick of the button if they answered "OK"
<script type = "text/javascript">
function Confirm() {
if (confirm("Selected item is on temporary back order. If you want to include it on this order click OK, then resubmit it?")) {
//had to resort to this to find hidden field rather than document.getElementById('confirm_value')
var x = document.getElementById('<%= confirm_value.ClientID%>');
x.value = 'Yes';
//re-click the button
document.getElementById('<%=bttnadd.ClientID%>').click();
} else {
var x = document.getElementById('<%= confirm_value.ClientID%>');
x.value = 'No';
}
}
</script>

ASP finds dropdown with 0 elements but the elements are there

I'm using ASP to look for the selected value in a dropdown box. The dropdown box choices are generated at load time. Here is the JavaScript for that:
function CreateDepartmentDropdown(data) {
var dropdown = document.getElementById("department_dropdown");
for (var i = 0; i < data.length; i++) {
var array = data[i].split(',');
var option = document.createElement("option");
option.value = array[0];
option.innerHTML = array[1];
dropdown.add(option);
}
}
And it looks like this:
Looks fine to me. Then I checked the HTML out too just to be sure:
That looks great too. Now here is where the issue comes up. When I press submit this delegate fires in C# (still only testing while making this):
void Activity_Submit_Click(object sender, EventArgs e)
{
int fye = Int32.Parse(fye_dropdown.Value);
String activity_name = activity_name_field.Value;
String activity_responsible = responsible_field.Value;
int department = Int32.Parse(department_dropdown.Value);
String activity_start = datepicker_start.Value;
String activity_end = datepicker_end.Value;
}
And when I debug this it stops at department saying that it's malformed. Looking at department_dropdown.Value in the immediate window turns up an empty string and the dropdown itself has 0 children.
Why would this return an empty response when the list is clearly there? How would I go about fixing this?
The client-side items won't get posted back to the server like this.
The easiest way is to Serialize the array as Json, put it in a hidden input element's value :
In your markup:
<asp:HiddenField runat="Server" ID="department_dropdown_items" cssclass="department_dropdown_items" />
<asp:HiddenField runat="Server" ID="department_dropdown_selected" cssclass="department_dropdown_selected" />
Your Javascript:
function CreateDepartmentDropdown(data) {
var dropdown = document.getElementById("department_dropdown");
for (var i = 0; i < data.length; i++) {
var array = data[i].split(',');
var option = document.createElement("option");
option.value = array[0];
option.innerHTML = array[1];
dropdown.add(option);
}
$(".department_dropdown_items").text(JSON.Stringify(data));
}
$(document).ready(function() {
$("form").submit(function(e) {
$(".department_dropdown_selected").text( $("#department_dropdown").value);
});
});
then use it in the code behind:
void Activity_Submit_Click(object sender, EventArgs e)
{
string[] data = new JavascriptSerializer().Deserialize<string[]>(department_dropdown_items.Value);
string selectedValue = department_dropdown_selected.Value;
int fye = Int32.Parse(fye_dropdown.Value);
String activity_name = activity_name_field.Value;
String activity_responsible = responsible_field.Value;
int department = Int32.Parse(department_dropdown.Value);
String activity_start = datepicker_start.Value;
String activity_end = datepicker_end.Value;
}
The code is not tested. Tell me if it's not working :)
So I ended up doing the following:
Make a Hidden asp element called department_dropdown_selected_value
Then in a Script tag I made the following function:
.
function GetDepartmentDropdownValue(sel) {
var hidden_field = document.getElementById('department_dropdown_selected_value');
hidden_field.value = sel.value;
}
Then in my HTML I did this: <select class="form-control" id="department_dropdown" onchange="GetDepartmentDropdownValue(this)">
Then I can just simply do this in C#: int department = Int32.Parse(department_dropdown_selected_value.Value);

retrieving anchor's color on server side

I am retrieving the color of the html anchor control on the server side. following is my tried code
Design:
<a id="lkdelete" onclick="SingleDel(this);" runat="server" style="font-weight:bold ">Delete</a>
Javascript:
function SingleDel(ctrl)
{
var row=ctrl.parentNode.parentNode;//to get row containing image
var rowIndex=row.rowIndex;//row index of that row.
var hsingle_del=document.getElementById('<%hsingle_del.ClientId %>');
hsingle_del.value=rowIndex;
var modalPopupBehaviorCtrl = $find('bmpe');
modalPopupBehaviorCtrl.set_PopupControlID("pnlPopup");
modalPopupBehaviorCtrl.show();
}
Vb.Net:
Dim pid As String = ""
For Each r As GridViewRow In gridview.Rows
Dim lnk As HtmlAnchor = CType(r.Cells(1).FindControl("lkdelete"), HtmlAnchor)
If lnk.Style("Color") = "Red" Then
pid = CType(r.FindControl("lblposid"), Label).Text
End If
Next
here at 1st row of gridview the color is red . but it returns "". any solution?
make few changes on your code. add a hidden field on your page.
function SingleDel(ctrl)
{
var rowIndex=ctrl.offsetParent.parentNode.rowIndex-1;
var hsingle_del=document.getElementById('<%=hsingle_del.ClientId %>');
hsingle_del.value=rowIndex;
var modalPopupBehaviorCtrl = $find('bmpe');
modalPopupBehaviorCtrl.set_PopupControlID("pnlPopup");
modalPopupBehaviorCtrl.show();
}
vb(instead of for loop)
pid = CType(gridview.Rows(hsingle_del.Value).FindControl("lblposid"), Label).Text

Access OwnerTableView ParentItem

It is my Vb.net code it works perfectly.
Protected Sub ChkTaxCheckedChanged1(ByVal sender As Object, ByVal e As EventArgs)
Dim chkTax As CheckBox
Dim gv1 As GridDataItem
chkTax = TryCast(sender, CheckBox)
gv1 = DirectCast(chkTax.NamingContainer, GridDataItem)
Dim txtAmount1 As Label = CType(gv1.OwnerTableView.ParentItem.FindControl("lblItemAmount"), Label)
End Sub
But now I want to achieve the same functionality in clientside using JavaScript.
Like :
function ChkTaxCheckedChanged1(sender, args) {
var check = sender.get_parent()..??????
}
Any one know how can I do this?
Try this.
<script>
function handleClick(sender,args) {
//i have used jquery so do not forgot add jquery reference
var checkboxid = sender.get_id();
var parentRow = checkboxid.parent().parent().parent().parent().parent().parent()[0].previousSibling;
$(parentRow).find('span').html('Your text comes here');
}
</script>

Getting asp:TextBox text property in codebehind from a web user control after a javascript update

Here is the scenario.
I have a simple page containing an asp:PlaceHolder.
<%# Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="TrainingPlan.aspx.vb" Inherits="TrainingPlan" %>
<%# Reference Control="ctlTask.ascx" %>
<%# Reference Control="ctlTaskheader.ascx" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
<div class="centered">
<h2><asp:Label ID="lblPlanTitle" runat="server" Text="Plan Title"></asp:Label></h2>
<hr />
<br />
<asp:ImageButton ID="imgbtnSave" runat="server" ImageUrl="~/Images/save.ico" />
<br />
<asp:PlaceHolder ID="PlanPlaceHolder" runat="server"></asp:PlaceHolder>
</div>
</asp:Content>
The placeholder on this page is populated with several rows of the same web user control. This web user control contains several textboxes. For each textbox in this web user control I have public properties to set and get the text value. In the page load event of the web user control I am adding onClick attributes to some of those textboxes like so.
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
txtTrainingStart.Attributes.Add("onClick", "txtTrainingStart_Click(" & txtTrainingStart.ClientID & ", " & txtTask.ClientID & ");")
txtTraineeBadgeNum.Attributes.Add("onClick", "txtTraineeBadgeNum_Click(" & txtTraineeBadgeNum.ClientID & ", " & txtTask.ClientID & ", " & txtTrainingStart.ClientID & ");")
txtTrainerBadgeNum.Attributes.Add("onClick", "txtTrainerBadgeNum_Click(" & txtTrainerBadgeNum.ClientID & ", " & txtTrainingComplete.ClientID & ", " & txtTask.ClientID & ", " & txtTraineeBadgeNum.ClientID & ", " & Session.Item("isTrainer").ToString.ToLower & ");")
txtDecertifyingOfficial.Attributes.Add("onClick", "txtDecertifyingOfficial_Click(" & txtDecertifyingOfficial.ClientID & ", " & txtTrainerBadgeNum.ClientID & ", " & txtTask.ClientID & ", " & Session.Item("isDecertifyingOfficial").ToString.ToLower & ");")
End Sub
For each of those onClick events I have corresponding javascript functions.
<script type="text/javascript">
function txtTrainingStart_Click(txtTrainingStart, txtTask) {
//processing and updates to textboxes here
}
</script>
Here is the problem.
On the main page containing the placeholder I have a save button. In the click event of the save button I am looping through each of the web user controls contained in the placeholder to process and save the data.
Protected Sub imgbtnSave_Click(sender As Object, e As ImageClickEventArgs) Handles imgbtnSave.Click
For Each item As Control In PlanPlaceHolder.Controls
Dim task As ctlTask = TryCast(item, ctlTask)
If Not IsNothing(task) Then
'need updated textbox values here.
'The following line gets the original textbox value, not the updated value that I need
Dim test As String = task.trainingStart
End If
Next
End Sub
Everything I have tried I can only get the original value that was in the textbox when the page loaded. I would think that this should be simple and I am just missing something basic. I've searched google high and low for the solution but I have yet to find one. This was the closest thing I found -> Set Text property of asp:label in Javascript PROPER way.
Although that post deals with a label rather than a textbox and isn't using a placeholder containing several web user controls. From what I understand I need to POST the updates back to the server from the client but I don't know how to do this. I've tried using the Request.Form property but I couldn't seem to make that work. What am I missing?
Thank you for any help,
Rylan
EDIT
Here is the code that populates the placeholder with the web user controls as requested
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim DBConn As MySqlConnection
Dim cmd As New MySqlCommand
DBConn = New MySqlConnection(Globals.mysqlConStr)
Try
lblPlanTitle.Text = Request.QueryString("plan_name") & " Training Plan"
If Session.Item("empID") = -1 Then
empID = clsUser.getID
Else
empID = Session.Item("empID")
End If
Dim strSQL As String = "SELECT * FROM task_revs tr WHERE tr.change != 'Deleted' and tr.id_plan = " & Request.QueryString("id_plan") & " ORDER BY task_num, rev_date desc"
Dim da As New MySqlDataAdapter(strSQL, DBConn)
Dim dtAllRevs As New DataTable
da.Fill(dtAllRevs)
Dim dtCurrentRev As New DataTable
Dim lastTaskNum As String = ""
dtCurrentRev = dtAllRevs.Clone
For Each row As DataRow In dtAllRevs.Rows
If lastTaskNum <> row("task_num") Then
dtCurrentRev.ImportRow(row)
lastTaskNum = row("task_num")
End If
Next
strSQL = "SELECT * FROM checkoffs WHERE emp_id = " & empID
da = New MySqlDataAdapter(strSQL, DBConn)
Dim dtCheckoffs As New DataTable
da.Fill(dtCheckoffs)
Dim addColor As Boolean = True
Dim tabWidth As Integer
Dim Header As ctlTaskHeader = LoadControl("ctlTaskHeader.ascx")
PlanPlaceHolder.Controls.Add(Header)
For Each row As DataRow In dtCurrentRev.Rows
Dim newRow As ctlTask = LoadControl("ctlTask.ascx")
tabWidth = 0
newRow.id_Task = row("id_Task")
newRow.taskNum = row("task_num")
newRow.task = row("task")
If row("is_header") = True Then
If row("task_num").ToString.EndsWith(".0") And row("task_num").ToString.Split(".").Count = 2 Then
newRow.taskBold = True
newRow.taskItalic = True
Else
newRow.taskForeColor = Drawing.Color.Blue
newRow.taskItalic = True
tabWidth += 10
End If
Else
tabWidth += 10
End If
For i As Integer = 0 To row("task_num").ToString.Split(".").Count - 3
tabWidth += 10
Next
newRow.TabSize = tabWidth
If Not IsDBNull(row("task_level")) Then
For i As Integer = 0 To row("task_level") - 1
newRow.taskLevel = newRow.taskLevel & "*"
Next
End If
If addColor = True Then
newRow.taskNumBackColor = Drawing.Color.LightGray
newRow.taskLevelBackColor = Drawing.Color.LightGray
newRow.taskBackColor = Drawing.Color.LightGray
newRow.trainingStartBackColor = Drawing.Color.LightGray
newRow.trainingCompleteBackColor = Drawing.Color.LightGray
newRow.traineeBadgeNumBackColor = Drawing.Color.LightGray
newRow.trainerBadgeNumBackColor = Drawing.Color.LightGray
newRow.decertifyingOfficialBackColor = Drawing.Color.LightGray
End If
addColor = Not addColor
For Each checkoff As DataRow In dtCheckoffs.Rows
If checkoff("id_task") = row("id_task") Then
If Not IsDBNull(checkoff("training_start")) Then
newRow.trainingStart = checkoff("training_start")
End If
If Not IsDBNull(checkoff("training_complete")) Then
newRow.trainingComplete = checkoff("training_complete")
End If
If Not IsDBNull(checkoff("trainee_badge")) Then
newRow.traineeBadgeNum = checkoff("trainee_badge")
End If
If Not IsDBNull(checkoff("trainer_badge")) Then
newRow.trainerBadgeNum = checkoff("trainer_badge")
End If
If Not IsDBNull(checkoff("decertifying_official")) Then
newRow.decertifyingOfficial = checkoff("decertifying_official")
newRow.taskNumBackColor = Drawing.Color.LightSalmon
newRow.taskLevelBackColor = Drawing.Color.LightSalmon
newRow.taskBackColor = Drawing.Color.LightSalmon
newRow.trainingStartBackColor = Drawing.Color.LightSalmon
newRow.trainingCompleteBackColor = Drawing.Color.LightSalmon
newRow.traineeBadgeNumBackColor = Drawing.Color.LightSalmon
newRow.trainerBadgeNumBackColor = Drawing.Color.LightSalmon
newRow.decertifyingOfficialBackColor = Drawing.Color.LightSalmon
End If
End If
Next
If row("is_header") = True And PlanPlaceHolder.Controls.Count > 1 Then
Dim newLine As LiteralControl = New LiteralControl("<br/>")
PlanPlaceHolder.Controls.Add(newLine)
End If
PlanPlaceHolder.Controls.Add(newRow)
Next
Catch ex As Exception
clsLog.logError(ex)
Finally
DBConn.Close()
End Try
EDIT 2
I thought it might also be important to show how I am making updates to the textboxes in my javascript functions
function txtTrainingStart_Click(txtTrainingStart, txtTask) {
var currentdate = new Date();
var datetime = (currentdate.getMonth() + 1) + "/" + currentdate.getDate() + "/" + currentdate.getFullYear() + " " + getTimeAMPM();
txtTrainingStart.value = datetime;
txtTrainingStart.style.backgroundColor = "yellow";
}
Edit 3:
The below code will work for static controls, but dynamically-created controls will not be preserved on postback. You will need to store the updated values so they can be retrieved on postback somehow (e.g. a Session variable or HiddenField). If possible, I would create the controls statically and populate them in page_load, hiding controls with no data - this would allow you to get the values on postback as below.
Hmm...I set up a super simplified version of your code and ran it pretty much as is (without the database function), and it seems to be working fine.
Here is the simplified version I used:
<asp:Content id="Content1" ContentPlaceHolderID="MainContent" runat="server">
<asp:ImageButton ID="imgbtnSave" runat="server"></asp:ImageButton>
<asp:PlaceHolder ID="PlanPlaceHolder" runat="server">
<asp:TextBox runat="server" ID="txtTrainingStart" value="before" ></asp:TextBox>
</asp:PlaceHolder>
</asp:Content>
Javascript:
function txtTrainingStart_Click(txtTrainingStart, txtTask) {
var currentdate = new Date();
var test = "after";
txtTrainingStart.value = test;
txtTrainingStart.style.backgroundColor = "yellow";
}
VB:
Protected Sub imgbtnSave_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs Handles imgbtnSave.Click
For Each item As TextBox In PlanPlaceHolder.Controls
'need updated textbox values here.'
Debug.WriteLine(item.ID)
Debug.WriteLine(item.Text)
Next
End Sub
I'm getting the updated value of the textbox, so you should be able to pass that value to a function and do whatever operations you need.
Let me know if I'm missing something.
Edit 2: I just had a thought--can you check if page_load is being called after you click the save button? I wonder if it is overwriting your updated values with the original values again.
If it is, I would wrap the database functionality in page_load with a postback check:
If Not IsPostBack
' connect to database'
' populate placeholder'
End If
I have figured it out. I was on the right track using Request.Form I just didn't fully understand how to use it yet.
New code for my save button
Protected Sub imgbtnSave_Click(sender As Object, e As ImageClickEventArgs) Handles imgbtnSave.Click
Dim coll As NameValueCollection
coll = Request.Form
For x = 0 To coll.Count - 1
Response.Write("Key = " & coll.GetKey(x) & " Value = " & coll(x) & "<br />")
Next
End Sub
The loop outputs all the control keys and updated values from the postback like so.
Key = ctl00$MainContent$ctl01$txtTrainingStart Value = 8/1/13
Key = ctl00$MainContent$ctl01$txtTrainingComplete Value = 8/2/13
Key = ctl00$MainContent$ctl02$txtTrainingStart Value = 8/3/13
Key = ctl00$MainContent$ctl02$txtTrainingComplete Value = 8/4/13
I use a hidden field to store a database row id with each dynamically created web user control. From that point it's easy to insert the updated values into my database.

Categories