Pass Expression Value to JavaScript function - c#

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

Related

"Error executing child request for handler 'System.Web.UI.Page'." while adding user control using JQuery

I am loading ASP.NET user control dynamically using JQuery:
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
var topics = xml.find("Topics");
topics.each(function () {
var table = $("#dvTopics table").eq(0).clone(true);
var customer = $(this);
$.ajax({
type: "POST",
url: "TopicList.aspx/LoadUserControl",
data: "{message: '" + topics.find("desid").text() + ",'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
table.append(r.d);
}
});
$("#dvTopics").append(table).append("<br />");
});
$("#loader").hide();
}
User Control code:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="TopicRow.ascx.cs" Inherits="TopicRow" %>
<link rel="stylesheet" type="text/css" href="Styles/Global.css" />
<asp:Panel ID="Panel1" runat="server" BorderColor="Maroon" Width="600px" style="margin:0">
<asp:LinkButton ID="Title" runat="server" Font-Bold="True" Font-Names="Segoe UI Semibold,Segoe UI Light, Tahoma, Geneva, Verdana, sans-serif" Font-Overline="False" ForeColor="Maroon" Text="This is a test title." Font-Size="Larger"></asp:LinkButton>
<br />
<asp:Label ID="lblAuthor" runat="server" Text="By: Aishwarya Shiva Pareek" Font-Size="Medium" ForeColor="#666666" Font-Names="Segoe UI Light, Tahoma, Geneva, Verdana, sans-serif"></asp:Label>
<br />
<br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate><div style="float:right; height:32px; width:32px"><asp:UpdateProgress ID="UpdateProgress2" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
<img alt="Working..." class="auto-style5" src="Images/ajaxloader.gif" width="32px" height="32px" />
</ProgressTemplate>
</asp:UpdateProgress></div>
<div style="font-family:Segoe UI Light, Tahoma, Geneva, Verdana, sans-serif">
Upvoted By
<asp:Label ID="lblUp" runat="server" Text="23"></asp:Label>
| Down voted By
<asp:Label ID="lblDown" runat="server" Text="2"></asp:Label>
<br />
<asp:LinkButton ID="lnkUp" runat="server" ForeColor="#003300" OnClick="lnkSupport_Click">Up Vote</asp:LinkButton>
<asp:LinkButton ID="lnkDown" runat="server" ForeColor="Red">Down Vote</asp:LinkButton>
<asp:LinkButton ID="lnkAddComment" runat="server" ForeColor="Maroon">Add Comment</asp:LinkButton></div>
</ContentTemplate>
</asp:UpdatePanel>
<hr style="color:maroon;"/>
</asp:Panel>
C# Code to add user control:
public static string LoadUserControl(string message)
{
using (Page page = new Page())
{
UserControl userControl = (UserControl)page.LoadControl("TopicRow.ascx");
(userControl.FindControl("Title") as LinkButton).Text = message;
page.Controls.Add(userControl);
using (StringWriter writer = new StringWriter())
{
page.Controls.Add(userControl);
HttpContext.Current.Server.Execute(page, writer, false);
return writer.ToString();
}
}
}
But at line HttpContext.Current.Server.Execute(page, writer, false); its showing:Error executing child request for handler 'System.Web.UI.Page'.exception. What can be the reason?
There is no json response from LoadUserControl server side script, you need to use json response.
The exception is thrown because you are using server side controls inside user control. ASP.NET requires that server side controls are inside a form control to render them properly, otherwise an exception is raised.
To get around this exception, you need to update your code, for exmaple like this:
HtmlForm form = new HtmlForm();
form.Controls.Add(userControl);
pageHolder.Controls.Add(form);
This will render your user control inside a form, which could be problematic. I suggest you to use a more cleaner approach without update panels and server side events.
Regards,
Uros

Reloading iframe in ASP.NET site from C# code

Trying to reload an iframe after C# has modified its attributes. Here's the page:
<script type="text/javascript">
function reloadFrame(Map) {
document.getElementById(Map).contentDocument.location.reload(true);
}
</script>
<asp:TextBox ID="TextBox1" placeholder="Zip code" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Find locations" onclick="Button1_Click" />
<iframe id="Map" runat="server"></iframe>
And when the button is clicked it runs this:
var zipCode = TextBox1.Text;
Map.Attributes.Add("src", "https://www.google.com/maps/preview#!q=gnc+near%3A+" + zipCode);
browser.Document.InvokeScript("reloadFrame", new[] { "Map" });
However the line to reload the iframe doesn't work. Any ideas?
How about setting the src for the iFrame via inline code?
<iframe id="Map" runat="server" src='<%= (TextBox1.Text == "" ? "" : "https://www.google.com/maps/preview#!q=gnc+near%3A+" + zipCode) %>'></iframe>

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

Want to be able to close a Modal Popup when clicked outside of it

I have a modal popup extender and a panel inside of an update panel. I do have a Close button which I bind with the CancelControlId. I however, would like to be able to click outside of my modal/panel to close the panel. (instead of using the close button).
I tried a couple things and a plugin clickoutside. Nothing seems to help. Any help or advice is much appreciated. Thanks.
<asp:Content ID="Content3" ContentPlaceHolderID="rightNavigation" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div id="mls_title" class="MLS_Title">
<asp:Label ID="lblTitle1" Text="Tasks" runat="server" class="MLS_titleLbl" /><br />
</div>
<asp:UpdatePanel ID="pnlMap" runat="server">
<ContentTemplate>
<div>
<asp:Button ID="btnMap" runat="server" Text="MAP" CausesValidation="false" CssClass="btnMap" />
<ajax:ModalPopupExtender
ID="ModalPopupExtender1"
runat="server"
TargetControlID="btnMap"
PopupControlID="panel1"
PopupDragHandleControlID="PopupHeader"
Drag="true"
BackgroundCssClass="ModalPopupBG">
</ajax:ModalPopupExtender>
<asp:Panel ID="panel1" runat="server">
<div class="popup_large">
<asp:Label ID="Label7" Text="Floor Plan" runat="server" stle="float:left"></asp:Label>
<asp:ImageButton ID="ImageButton1" runat="server" ToolTip="No" ImageUrl="~/Images/no.png" Style="float: right; margin-right: 20px" />
<br />
<asp:ImageButton ID="img" runat="server" Height="30em" Width="45em" />
</div>
</asp:Panel>
</div>
</ContentTemplate>
</asp:UpdatePanel>
Here is a link to an example that adds to the background onclick to close the modal:
http://forums.asp.net/t/1528820.aspx
Copied the key bits here for reference:
function pageLoad() {
var mpe = $find("MPE");
mpe.add_shown(onShown);
}
function onShown() {
var background = $find("MPE")._backgroundElement;
background.onclick = function() { $find("MPE").hide(); }
}
<AjaxToolKit:ModalPopupExtender ID="mdlPopup" BehaviorID="MPE" runat="server"
TargetControlID="btnShowPopup" PopupControlID="pnlPopup"
CancelControlID="btnClose" BackgroundCssClass="modalBackground" />
C#
<AjaxToolKit:ModalPopupExtender .... BackgroundCssClass="jsMpeBackground" />
JavaScript (using jQuery)
jQuery('.jsMpeBackground').click(function () {
var id = jQuery(this).attr('id').replace('_backgroundElement', '');
$find(id).hide();
});
I had to do it this way so that I was able to click the actual popup without it closing, as I have functional user controls such as tab sections and textboxes on the popup.
<script type="text/javascript">
//Hide's Doc Center when clicking outside
function pageLoad(sender, args) {
if (!args.get_isPartialLoad()) {
$addHandler($find("MPE")._backgroundElement, "click", closePopup);
}
}
function closePopup(e) {
$find("MPE").hide();
}
//End
</script>
Now just make sure your BehaviorID in your actual ModelPopupExtender matches up with the tag above. Like so:
<ajaxToolkit:ModalPopupExtender ID="Popup" runat="server" PopupControlID="Container" BehaviorID="MPE" TargetControlID="fakeTargetControl" BackgroundCssClass="modalBackground" CancelControlID="btnCancel" />
Basically I think this just handles the 'click' event of the _backgroundElement attr of the modal popup, and on that event runs the closePopup() function.
write a dynamically created script that is added, in my example, when the modal popup extender is loaded. Note: In order to bind this event handler to the ModalPopupExtender.OnLoad event, you need to add a reference (in client-side code, you can add 'OnLoad="mpeExample_Load"' to your ModalPopupExtender tag).
protected void mpeExample_Load(object sender, EventArgs e) {
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"hideModalPopupViaClient", String.Format(#"function hideModalPopupViaClient() {
{
var modalPopupBehavior = $find('{0}');
if (modalPopupBehavior) modalPopupBehavior.hide();}}",
mpeExample.ClientID), true);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "pageLoad", String.Format(#"function pageLoad() {
{
var backgroundElement = $get('{0}_backgroundElement');
if (backgroundElement) $addHandler(backgroundElement, 'click', hideModalPopupViaClient);
}}",
mpeExample.ClientID), true);}

My javascript variable is becoming undefined between function calls

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.

Categories

Resources