My javascript variable is becoming undefined between function calls - c#

I have a form that calls some javascript and some code behind (C# for me) when a link button is pressed. Normal operation should act as such: Click on link button which gets text from a label on the form, opens an HTML editor, save the text by clicking 'Done' on the text editor and then displaying the text on the form again. It will do all of that, but I get an error (control is undefined) and then that prevents me from doing any other work on the form.
First, here is my aspx code, which is a window that hold the HTML editor, and the HTML editor.
<asp:Panel ID="EditCommentPopup" runat="server" SkinID="PopupPanel" HorizontalAlign="Center" Width="500px" Style="display:none;">
<div id="SendCommentHeader" class="modalPopupHeader">
<table width="100%" style="vertical-align: middle">
<tr>
<td style="width: 50%; text-align: left; padding-left: 5px;">
<asp:Label ID="EditCommentHeaderLBL" runat="server" Font-Bold="true" Text="Change Comment" ></asp:Label>
</td>
<td style="width: 50%; text-align: right; padding-right: 3px;">
<asp:Button SkinID="SubmitButton" ID="SaveComment" runat="server" Text="Done" OnClientClick="submitEditorPopup(); return true;" OnClick="SubmitCommentButton_Click"/>
<asp:Button SkinID="CancelButton" ID="cancelCommentButton" runat="server" Text="Cancel"/>
</td>
</tr>
</table>
</div>
<ajaxToolkit:ModalPopupExtender ID="EditCommentPopupExtender" runat="server" TargetControlID="EditCommentHeaderLBL"
PopupControlID="EditCommentPopup" BackgroundCssClass="modalBackground" PopupDragHandleControlID="EditCommentPopup"
DropShadow="False" CancelControlID="cancelCommentButton" BehaviorID="ChangeCommentsPopup" >
</ajaxToolkit:ModalPopupExtender>
<asp:Panel ID="EditCommentInnerPanel" SkinID="PopupInnerPanel" HorizontalAlign="Center" runat="server" >
<asp:Label ID="CommandArgLBL" runat="server" Visible="false"></asp:Label>
<custom:CustomTextEditor ID="EditCommentsTextBox" runat="server" Width="100%" Height="300px" NoScript="true" />
</asp:Panel>
</asp:Panel>
Here are my javascript functions
var contentLBL;
var editorControl;
var hiddenField;
function LoadEditorPopup(labelID, editorID, hiddenID, linkID) {
editorControl = document.getElementById(editorID);
contentLBL = document.getElementById(labelID);
hiddenField = document.getElementById(hiddenID);
editorControl.control.set_content(contentLBL.innerHTML);
var popup = $find("ChangeCommentsPopup");
popup.show();
}
function submitEditorPopup() {
var tmp = editorControl.control.get_content(); //error flags here
contentLBL.innerHTML = tmp;
var str= new String();
str = tmp;
str = str.replace(/</g, "{%");
str = str.replace(/>/g, "%}"); //stripping out html tags to prevent sql insertion
hiddenField.value = str;
var popup = $find("ChangeCommentsPopup");
popup.hide();
}
And here are my C# functions
protected void ShowEditCommentPopup(object sender, EventArgs e)
{
string arg = ((LinkButton)sender).CommandArgument;
string content = "";
string title = "";
switch (arg)
{
//doing stuff, setting content and title
}
EditCommentHeaderLBL.Text = title;
CommandArgLBL.Text = arg;
EditCommentsTextBox.Content = content;
EditCommentPopupExtender.Show();
EditModalPopupExtender.Show(); //this is the form
}
So, what's happening here, I click on a linkbutton (not shown in aspx code) and it fires the LoadEditorPopup function in the javascript. It does its stuff and I have a 'return true' in the onclientclick call so that the next function, ShowEditCommentPopup, in the code behind, will be called. The editor pops up and I can use it just fine. When I click 'Done' the SubmitEditorPopup event is fired in the javascript and I get an error saying that the variable EditorControl is undefined. I have found that if I do not call the ShowEditCommentPopup method, the error does not occur, but then I get back to another problem I had originally, which I'm hoping that will be fixed if this problem is fixed.
I really hope that was clear enough. Thanks in advance!

You have a snippet with your javascript functions. Where does that code live? It it inside a class or function that could be getting called a second time? If so, var editorControl; could be getting run again and override your previous editorControl variable. I would put an alert right about var editorControl; to make sure.
alert( 'Should only happen once' );
var editorControl;
Since that didn't help, I guess you could try replacing
var tmp = editorControl.control.get_content();
with
tmp = document.getElementById(editorID);
in submitEditorPopup.

Related

How to add C# variables to html modal

In my ASP.Net app, I have a button that launches a modal. The onClick event fires the C# behind code that launches a modal. I am then calling a data table and populating string variables with values from the data table:
protected void uxTicketHistoryButton_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "key", "launchModal();", true);
DataTable ticketHist = _dtMgr.GetContactInfoByName(uxContactDropdownList.SelectedValue);
string rName = ticketHist.Rows[0]["RequestorName"].ToString();
string rPhone = ticketHist.Rows[0]["RequestorPhone"].ToString();
string rPhoneExt = ticketHist.Rows[0]["RequestorPhoneExt"].ToString();
string rEmail = ticketHist.Rows[0]["RequestorEmail"].ToString(); ;
string rState = ticketHist.Rows[0]["RequestorState"].ToString();
string rOrg = ticketHist.Rows[0]["RequestorOrg"].ToString();
}
What I want to do now is add those variable values to my modal inside the panel.
<asp:Button ID="uxTicketHistoryButton" runat="server" Text="Show Ticket History" style="color: blue;" OnClick="uxTicketHistoryButton_Click"/>
<!-- ModalPopupExtender-->
<ajaxToolkit:ModalPopupExtender ID="uxTicketHistoryModal" runat="server" PopupControlID="Panel1" TargetControlID="uxTicketHistoryButton"CancelControlID="btnClose" BackgroundCssClass="modalBackground">
</ajaxToolkit:ModalPopupExtender>
<asp:Panel ID="Panel1" runat="server" CssClass="modalPopup" align="center" style = "display:none">
**** Add variable values here ****
<asp:Button ID="btnClose" runat="server" Text="Close" />
</asp:Panel>
How do I add the variables from my .cs file to the modal panel in my .aspx file so that it shows up like this (values in the { } )?
UPDATE
This issue seems to be related to the modal interfering with the _Click event function of my button. I have posted an additional question to resolve this problem first. Then, I believe one of the solutions below may work. Thanks everybody!
Webform:
<asp:Panel ID="Panel1" runat="server" CssClass="modalPopup" align="center" style = "display:none">
Name: <asp:Literal ID="Name" runat="server" /><br>
Organization: <asp:Literal ID="Organization" runat="server" /><br>
etc....
<asp:Button ID="btnClose" runat="server" Text="Close" />
</asp:Panel>
Codebehind:
Name.Text = ticketHist.Rows[0]["RequestorName"].ToString();
Organization.Text = ticketHist.Rows[0]["RequestorOrg"].ToString()
You can use ASP.NET Razor to post your c# variables directly into your html.
For Example
<!-- Single statement block -->
#{ var myMessage = "Hello World"; }
<!-- Inline expression or variable -->
<p>The value of myMessage is: #myMessage</p>
<!-- Multi-statement block -->
#{
var greeting = "Welcome to our site!";
var weekDay = DateTime.Now.DayOfWeek;
var greetingMessage = greeting + " Here in Huston it is: " + weekDay;
}
<p>The greeting is: #greetingMessage</p>
OR
you could use get and set methods to post your variables to the modal from you .cs .
public class yourModalPage
{
public string RequestorName { get; set; }
}
Then you can send values to your modal from your .cs with
yourModalPage.RequestorName = "RequestorName";

label text set in javascript not showing label text on server side

I know my question is duplicate of here but still facing problem
In my javascript code I have tried different way of assigning text to label are
function fileuploadvalidation() {
document.getElementById("<%=lableid.ClientID%>").Text = "hello";
document.getElementById("<%=lableid.ClientID%>").innerHTML = "hi";
}
and its use to be seen text on my .aspx page also but when I used to fetch that text on my server side it is coming blank.
.html page code
<asp:UpdatePanel ID="UpdatePanel16" runat="server"><ContentTemplate>
<asp:Button ID="btn_browse" runat="server" Text="Upload" OnClick="btn_browse_Click" OnClientClick="return fileuploadvalidation();" />
<asp:Label ID="lableid" runat="server" Text="" Style="font-size: small; font-weight: 400;font-family: Arial, Helvetica, sans-serif"></asp:Label>
</ContentTemplate></asp:UpdatePanel>
.cs code
protected void btn_browse_Click(object sender, EventArgs e)
{
string abc = lableid.Text;// This is coming null
}
Use hidden-field to store the value that you set,then access it in code behind
add a hidden field
<input type="hidden" id ="hiddenfieldid" runat="server" />
.
function fileuploadvalidation() {
document.getElementById("lableid").value = "hello";
document.getElementById('hiddenfieldid').value= "hello";
}
then retrieve it in code behind.
string abc = hiddenfieldid.value;
I think you want to add set the value property of the label
var lbl = document.getElementById("<%=lableid.ClientID%>")
lbl.value = "hello";
try to use this
$('#lableid').val($('#lableid').val().replace($('#lableid').val(), "hello"));

Read label value in code behind

Am using the below code to assign the label text using javascript. It's working well. But i can't able to read the label text in code behind. Please help me to fix this issue.
Javascript:
==========
var lbl_total = document.getElementById('<%= lbl_total.ClientID %>');
lbl_total.innerHTML = '500';
c# code behid :
===============
string total = lbl_total.Text; //It always return "";
client side changes for label will not get reflected in server side as its data is not posted to server. So the solution is to take an input hidden control and set its value with label's updated value. Below is the sample code:
<script type="text/javascript">
$(document).ready(function() {
var total = 0;
$('#Button1').click(function() {
total += 150;
$("span[id$=lbl_TotalCount]").html(total);
$("input:hidden[id$=MyHidden]").val(total);
});
});
</script>
html
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="button" />
<asp:Button ID="btn_saveForm" runat="server" Text="save" CssClass="btnForm" OnClick="btn_saveForm_Click" />
<asp:Label ID="lbl_TotalCount" Style="color: #00e4ff; font-family: Arial; font-weight: bold;
text-decoration: underline" runat="server" Text="0">
</asp:Label>
<asp:HiddenField ID="MyHidden" runat="server" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
full Article : Get label value in code behind whose text is changed via JavaScript/jQuery

"Invalid Postback" exception on custom GridView with custom row events

I think I have figured out what happens with this program.
This is part of the markup.
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:UpdatePanel ID="upGrid" runat="server">
<ContentTemplate>
<asp:GridView ID="dgvPeliculas" runat="server" AllowPaging="true" PagerStyle-CssClass="pgr"
CssClass="mGrid" EmptyDataText="No hay más películas" OnPageIndexChanging="dgvPeliculas_PageIndexChanging1"
EnableSortingAndPagingCallbacks="true" OnRowDataBound="dgvPeliculas_RowDataBound">
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<table class="LogIn">
<tr>
<td>
<asp:UpdatePanel ID="upAlquiler" runat="server">
<ContentTemplate>
<asp:Button ID="btnAlquilar" runat="server" Text="Alquilar" CssClass="AdminButtons"
OnClick="btnAlquilar_Click" OnClientClick="javascript: Click_Alquilar(); return false" />
</ContentTemplate>
</asp:UpdatePanel>
</td>
<td>
<asp:Button ID="btnNuevo" runat="server" Text="Nuevo" CssClass="AdminButtons" OnClick="btnNuevo_Click"
OnClientClick="javascript: Click_Nuevo(); return false" />
</td>
<td>
<asp:Button ID="btnEditar" runat="server" Text="Editar" CssClass="AdminButtons" OnClick="btnEditar_Click"
OnClientClick="javascript: Click_Editar(); return false" />
</td>
<td>
<asp:Button ID="btnBorrar" runat="server" Text="Borrar" OnClientClick="javascript: Click_Borrar(); return false"
CssClass="AdminButtons" />
</td>
</tr>
</table>
I have coded it in such a way that the buttons modify it when a row is selected. The rows are selected by changing the "onclick" event (changed during the RowDataBound function), and a Javascript function.
This is how I change the code behind:
protected void dgvPeliculas_RowDataBound(object sender, GridViewRowEventArgs e)
{
dgvPeliculas.CssClass = "mGrid";
if (e.Row.RowType == DataControlRowType.DataRow)
{
string rowID = String.Empty;
rowID = "row" + e.Row.RowIndex;
e.Row.Attributes.Add("id", rowID);
e.Row.Attributes.Add("onclick", "onClick(" + "'" + rowID + "'" + ")");
e.Row.Attributes.Add("onmouseover", "this.style.cursor='pointer'; this.style.backgroundColor = '#B0C5BB';");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor = '';");
}
}
This is the JavaScript function:
/
function onClick(rowID)
{
//Si no hay ninguna seleccionada
if (selected == '') {
index = rowID;
selected = document.getElementById(rowID);
selected.onmouseover = '';
selected.onmouseout = '';
selected.style.backgroundColor = 'yellow';
}
else {
//Si se deselecciona
if (selected == document.getElementById(rowID)) {
selected.onmouseover = onmouseover;
selected.onmouseout = onmouseout;
selected.style.backgroundColor = '';
selected = '';
index = '';
}
//Deseleccionar el actual y seleccionar el nuevo
else {
selected.onmouseover = onmouseover;
selected.onmouseout = onmouseout;
selected.style.backgroundColor = '';
index = rowID;
selected = document.getElementById(rowID);
selected.onmouseover = '';
selected.onmouseout = '';
selected.style.backgroundColor = 'yellow';
}
}
}
The New button shows a ModalPopupExtender, and from there it calls a JavaScript function to validate its contents, and then does a postback to code behind to check and update the database. It also appends the register on the Grid, obviously.
The Edit button and the rest through the exception. The Edit function is particular, because its functionality is similar to that of the New button. It shows the ModalPopupExtender, goes to the JavaScript function, does the postback, to the database and updates. But this one needs to have one of the rows in the Grid selected (otherwise, there's nothing to be edited). I believe this is the reason why it throws the "Invalid Postback or Callback" exception. The same condition applies to the other buttons, and all of them throw the same exception. All, except New, which doesn't need to have a row selected.
Do you think this is the reason why I'm having this problem? And if so, how can I fix it?
Sorry if you consider this a repost of one of my previous threads, but I haven't been able to fix the problem, and I think this gives me a new clue that I can't work out neither.
Thanks.

Pass Expression Value to JavaScript function

I have this following code, here CssClass is of the String type.
<asp:Panel ID="Panel1" runat="server" title="<%# Title %>" class="<%# CssClass %>">
<asp:Panel ID="Panel2" runat="server" Style="padding-top: 20px; color: Red">
Invalid Credential
</asp:Panel>
<asp:Panel ID="Panel3" runat="server" Style="text-align: center; padding-top: 50px;">
<telerik:RadButton ID="LoginFaild" runat="server" Text="Ok" Font-Size="14px" Width="100px"
OnClientClicked='<%# "function(button, args){closeDialog(" + CssClass + ");}" %>' />
</asp:Panel>
Now I want to pass this String value to the JavaScript function closeDialog() which is:
var closeDialog = function (className) {
$("." + className).dialog("close");
}
When I am clicking on the button I am getting
loginError is not defined
in my Web Developer's Toolbar of Firefox.
How can I solve this problem?
Assuming that CssClass is set in c#, you do not need to specify the inline CssClass property in the close dialog constructor. Change your closeDialog function to:
var closeDialog = function () {
$("." + <%= CssClass %>).dialog("close");
}
Then your OnClientClicked event can be rewritten as:
OnClientClicked="function(button, args){ closeDialog(); };" or OnClientClicked="closeDialog();"
EDIT:
Script at the Top of the Page
var cssClass = '<%= CssClass %>';
Close Dialog Function
var closeDialog = function () {
$("." + cssClass).dialog("close");
}

Categories

Resources