i have a radwindow that is being opened by a view column from a rad grid. but the thing is that nothing is happening , the window is not even opening!!!
i want to passe 2 parameters to the RadWindow.
this is the javascript im using:
function ShowEditForm(IdVoiture, IdType, rowIndex) {
var grid = $find("<%= RadGrid1.ClientID %>");
var rowControl = grid.get_masterTableView().get_dataItems()[rowIndex].get_element(); grid.get_masterTableView().selectItem(rowControl, true);
window.radopen("ViewForm.aspx?IdVoiture=" + IdVoiture, "&IdType=" + IdType,"UserListDialog");
return false;
}
and this is my column code from the radGrid:
<telerik:GridTemplateColumn UniqueName="TemplateViewColumn">
<ItemTemplate>
<asp:HyperLink ID="ViewLink" runat="server" Text="View"></asp:HyperLink>
</ItemTemplate>
</telerik:GridTemplateColumn>
this is the code behind:
Protected Sub RadGrid1_ItemCreated(ByVal sender As Object, ByVal e As GridItemEventArgs)
If TypeOf e.Item Is GridDataItem Then
Dim editLink As HyperLink = DirectCast(e.Item.FindControl("ViewLink"), HyperLink)
editLink.Attributes("href") = "#"
editLink.Attributes("onclick") = [String].Format("return ShowEditForm2('{0}','{1}');", e.Item.OwnerTableView.DataKeyValues(e.Item.ItemIndex)("DepIDVoit"), 4, e.Item.ItemIndex)
End If
End Sub
i'm not able to locate my error and i tried to do the same as other examples it is still not working please help!!!
****Mark that my code is in an .ascx page contained inside an multipage in a .aspx page , and the javascript is in the .aspx page i dont know if that makes any differencs
i figured out what was missing. my javascript code was correct but my page was missing a RadWindowManager
Related
I am now creating a web site with webforms in C#. I made a button that opens the child window with a landscape photo if pressed. On top of the landscape painting in the child window, comments written in the parent window are displayed.
The user can press this button to open as many child windows as they press, separate from the ASPX page with this button. Just press the button 10 times to open 10 pages of child windows with pictures of landscape paintings.
What I want to do is not press the button 10 times to create 10 child windows, but I want to update the child window 9 times after the child window is created in the first time.
If possible, I'd like you to tell me how to do it. Also, I thought that it would be difficult for me to do so, so I thought that if I pressed the button after the second time, the old child window created by pressing the button before that would close and a new child window would be born.
Below is the code I wrote.
↓aspx
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
↓aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
string url=string.Format("WebForm1.aspx?q={0:s}",TextBox1.Text);
Type cstype = this.GetType();
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(cstype, "OpenNewWindow", "window.open('" + url + "', null);",true);
}
The problem is twofold. One way is to update the child window. The other way is to close the child window. I thought that the line window would be closed with the code below, so I tried it lightly, but the parent window closed and the child window remained.
↓aspx.cs
protected void Button2_Click(object sender, EventArgs e)
{
string url=string.Format("WebForm1.aspx?q={0:s}",TextBox1.Text);
Type cstype = this.GetType();
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(cstype, "CloseNewWindow", "window.Close('" + url + "', null);",true);
}
What should I do?
I think you best consider having this pop up appear on the CURRENT page.
And now that you want to restrict to "one", then that makes this a WHOLE lot less work.
There are more "dialog" systems then flavors of ice cream to choose from.
but, the two most common are the bootstrap ones, and the one from jQuery.UI.
I find the jQuery.UI VERY easy to work with - and you can control position with much greater ease then bootstrap ones.
And given that you have a SUPER high chance of already having jQuery, then adopting jQuery.UI from the same folks makes all the more sense.
And jQuery.UI dialogs can be "modal", and that means focus can't get out of the dialog until you "ok" or "save" or whatever.
So, lets take a simple GridView. Say we have some rows, and a "image".
When we click on the edit button, we pop a dialog with the picture, and also allow you to edit the comments.
So, our Grid is say this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table" >
<Columns>
<asp:BoundField DataField="Fighter" HeaderText="Fighter" />
<asp:BoundField DataField="Engine" HeaderText="Engine" />
<asp:BoundField DataField="Thrust" HeaderText="Thrust" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:ImageButton ID="cmdView" runat="server" Width="150px"
ImageUrl = '<%# Eval("ImagePath") %>'
OnClick="cmdView_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code on page load is thus this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
SqlCommand cmdSQL = new SqlCommand("SELECT * FROM Fighters");
GridView1.DataSource = MyRstP(cmdSQL);
GridView1.DataBind();
}
And now we have this:
So, the way jQuery.UI works?
You create a simple "div" on the same page, and it will become your "dialog"
You then hide with style=display:none.
So our markup for this "div" to disaplay the picture "big" and edit comments is this
(we drop it below the GV)
So, we have this simple markup to display picture, and let user edit comments for the picture:
<div id="EditOne" runat="server" style="text-align:center;display:none" clientidmode="static">
<br />
<asp:Image ID="Image1" runat="server" width="90%" />
<br />
<h4>Edit Description</h4>
<asp:TextBox ID="txtDescription" runat="server"
TextMode="MultiLine" Columns="90" Height="100px">
</asp:TextBox>
<br />
</div>
<asp:Button ID="cmdSave" runat="server" Text="Save" ClientIDMode="Static"
style="display:none" OnClick="cmdSave_Click"/>
Note careful in above - right below the div, I have a hidden save button.
So, now the jQuery routine that we pop to display this div as a dialog:
this:
<script>
function popimage(btn) {
pWidth = "50%"
myDialog = $("#EditOne");
myDialog.dialog({
title: "Edit Comments",
modal: true,
width: pWidth,
closeText: "",
show: "fade",
buttons: {
Save: function () {
myDialog.dialog("close")
$('#cmdSave').click()
},
Cancel: function () {
myDialog.dialog("close")
}
}
})
}
</script>
So, now we only need our button row click from the grid (I used image button).
That code is this:
We get the current row PK id, pull from database, and fill out the "div", and then pop it:
protected void cmdView_Click(object sender, ImageClickEventArgs e)
{
ImageButton btn = (ImageButton)sender;
GridViewRow gRow = (GridViewRow)btn.NamingContainer;
int PK = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM Fighters WHERE ID = #ID");
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PK;
DataTable rstFighter = MyRstP(cmdSQL);
Image1.ImageUrl = rstFighter.Rows[0]["ImagePath"].ToString();
txtDescription.Text = rstFighter.Rows[0]["Description"].ToString();
ViewState["rstFighter"] = rstFighter;
Page.ClientScript.RegisterStartupScript(
this.GetType(),"MyEdit","popimage()", true);
}
And now our save button, to send information back to database is this:
protected void cmdSave_Click(object sender, EventArgs e)
{
// Save comments (and other fields back to database)
DataTable rstFigher = (DataTable)ViewState["rstFighter"];
rstFigher.Rows[0]["Description"] = txtDescription.Text;
SaveData(rstFigher, "Fighters");
LoadGrid(); // refresh grid to show any edits
}
So, the results now look like this when I click on a row image:
Note how the web page behind goes "darker gray" and the pop up is model.
So, I would consider jQuery.UI dialogs.
And I did use two helper routines (after all, we don't write the same code over and over to get get a simple data table, right???).
Those two helper routines were:
DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
void SaveData(DataTable rstData,string sTable)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM " + sTable, conn))
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
da.Update(rstData);
}
}
}
So, as above shows you have complete control over closing the pop up dialogue, but MUCH more important we can then also with ease update the current page to reflect those changes ( in our example update the description text in our pick list GridView). And with both the grid display and editing on the same page we also require much less code.
I'm trying to add an error label to the top of a panel I have. I have a button created in C# on page load that calls a JavaScript function that I want to display an error message on my panel when clicked.
C#:
private void CreateButton(int pID, string changeType)
{
ASPxButton btn = new ASPxButton();
btn.Text = "Execute Request";
btn.ID = "btn" + changeType;
btn.AutoPostBack = false;
btn.ClientSideEvents.Click = GetClientSideEventHandler(string.Format("OnProcessRequest(s, e, '{0}','{1}')", pID.ToString(), changeType));
TableRow oRow = new TableRow();
TableCell oCell = new TableCell();
oCell.CssClass = "table-cell";
oCell.Controls.Add(btn);
oRow.Cells.Add(oCell);
tblButtons.Rows.Add(oRow);
}
JS:
function OnProcessRequest$(pID, pChangeType) {
document.getElementById('errLabel').value = "Test";
}
ASPX:
<asp:Label ID="errLabel" runat="server"/>
When this code runs, it always throws the following error:
Error: Unable to set property 'value' of undefined or null reference.
I have tried also using:
document.getElementById('<%=errLabel.ClientID%>').value = "Test";
but this also throws the error.
How can I change the value of this label when this button is clicked in JS?
Ok, to change a asp.net label in JavaScript, you can do this:
(we assume you set the label client id mode>
So, if we have label on the page, you can do this:
<asp:Label ID="Label1" runat="server" Text="" ClientIDMode="Static"></asp:Label>
JavaScript to change above is this:
var lbl = document.getElementById('<%=Label1.ClientID%>');
lbl.innerText = "Js lable text changed";
Or
lbl.innerHTML = "<h2>this is some big text by js</h2>"
Be VERY careful with case, and VERY careful with extra spaces etc. in the get Element.
Also, do NOT forget to include the Text="" in your label!!!! (you are missing this!!!).
JavaScript is VERY flakey - one small wrong move, and it just rolls over and goes home. (and the debugger in browsers is on par with a trip to the dentist).
You can also use jQuery.
The above thus becomes this:
var lbl = $('#Label1');
lbl1.text("js jquery text change");
Now, lets do the same for a text box.
our asp.net text box:
<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static" ></asp:TextBox>
JavaScript:
var txt = document.getElementById('<%=TextBox1.ClientID%>');
txt.value = "This is js text for text box";
And as jQuery:
var txt = $('#TextBox1');
txt.val("js jquery text for the text box");
So, for a asp.net label? You use innerText, or innerHTML.
(or text("your text here") with jQuery)
and with jQuery, you use .value without ()
Try adding ClientIDMode="Static" to your label if that property is available to you. Or you could add ClientID="errLabel" as an alternative. What's happening is asp.net will automatically give your field a generated id for closure on the client side so it will not match your id "errLabel".
<asp:Label runat="server" ID="errLabel" ClientIDMode="Static"></asp:Label>
OR
<asp:Label runat="server" ID="errLabel" ClientID="errLabel"></asp:Label>
https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.control.clientidmode?view=netframework-4.8#System_Web_UI_Control_ClientIDMode
I have 2 pages in asp.net with c# .
a parent.aspx and popup.aspx.
I passed a querystring(id) into page load of popup.aspx and used function to call row of table base on id and show gridview on popup.aspx.
now I want to select this row, and pass details into text boxes of parent.aspx that is open now.
Everything is ok and row of table is passed into text boxes, but it is into new window popup of parent.aspx page, that I don't want this.
I want pass details into this page(parent.aspx) that now is open.
How can I do that.thanks.
below is my code for pass id to pop-up window
protected void btn_search_id_Click(object sender, ImageClickEventArgs e)
{
string str1 = Encrypt(txt_sh_p.Text);
btn_search_id.Attributes.Add("onclick", "window.open('popup.aspx?sh_p_=" + str1 + "','Report','width=750,height=500,toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,left=200,top=50'); return false;");
}
my code for reading id and select row and display row in gridview on page load event of popup.aspx:
protected void Page_Load(object sender, EventArgs e)
{
DAL.Sab_Ashkh sabt_ashkh = new DAL.Sab_Ashkh();
List<DAL.Sab_Ashkh> sabt_ashkh_list;
sabt_ashkh.sh_p = Decrypt(Request.QueryString["sh_p_"]);
sabt_ashkh_list = sabt_ashkhDB.GetShakh_find(sabt_ashkh.sh_p);
grid_ashkh.Visible = true;
grid_ashkh.DataSource = grid_ashkh_list;
grid_ashkh.DataBind();
}
and html code for pass row to parent page:
<Columns>
<asp:HyperLinkField DataTextField="id_shakh" DataNavigateUrlFields="id_shakh" DataNavigateUrlFormatString="parent.aspx?id_shakh={0}"
HeaderText="id" ItemStyle-Width = "150" />
<asp:TemplateField HeaderText="select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width = "150px" DataField = "sh_p" HeaderText ="kod"
>
<ItemStyle Width="150px"></ItemStyle>
</asp:BoundField>
</Columns>
I am just telling you how you can change the variable in Main page in popup page like:
Suppose Parent.aspx have:
<script type="text/javascript">
var items =[];
</script>
and in popup.aspx you can do something like :
window.opener.items.push(yourSelectedRows);
but as another workaround you can also use local storage like:
localStorage.setItem("selectedRecords", JSON.stringify(selectedRows));
suppose selectedRows are your array of object or anything else but as my experience the selectedRecords would be accessible in all HTML pages.
hope this help you.
Hi Aria Thanks for reply. I pass id by query string into popup window and show gridview . and this script for popup win :
<script type="text/javascript">
function SetName() {
if (window.opener != null && !window.opener.closed) {
var txtName = window.opener.document.getElementById("txt_id_mah");
grid = document.getElementById("grid_ashkh");
var cellPivot;
if (grid.rows.length > 0) {
for (i = 1; i < grid.rows.length; i++) {
cellPivot = grid.rows[i].cells[1];
TXT.value = cellPivot;
}
}
}
window.close();
}
</script>
but does not work.
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.
I have two javascript functions in my aspx page. They use some fabric.js functions.
function saveCanvas() {
js = JSON.stringify(canvas.toDatalessJSON());
$get('<%= txtJSON.ClientID%>').value = js;
}
function loadCanvas() {
js = $get('<%= txtJSON.ClientID%>').value;
canvas.clear();
canvas.loadFromDatalessJSON(js);
canvas.renderAll();
}
And in the codebehind:
Protected Sub SaveJSON()
Dim scriptKey As String = "123"
Dim javaScript As String = "<script type='text/javascript'>saveCanvas();</script>"
ClientScript.RegisterStartupScript(Me.GetType(), scriptKey, javaScript)
End Sub
Protected Sub LoadJSON()
Dim scriptKey As String = "456"
Dim javaScript As String = "<script type='text/javascript'>loadCanvas();</script>"
ClientScript.RegisterStartupScript(Me.GetType(), scriptKey, javaScript)
End Sub
Now my question: Why does loadCanvas work while saveCanvas does not? txtJSON is not populated with the JSON-string.
Calling the saveCanvas function from the aspx page works fine.
The problem is that you call saveCanvas after the postback is done and at that point the canvas data is long gone.
If you have a button "Save" then you need to call saveCanvas when it is clicked so that the data is saved before the browser posts the page back to the server:
<asp:Button runat="server" Text="Save" OnClickClick="saveCanvas()" />