Calling C# getter from UpdatePanel / javascript - never get updated data - c#

I have this property in my code-behind.
public string LocationOptions
{
get { return Session["LocationOptions"].ToString(); }
set { Session["LocationOptions"] = value; }
}
On the front-end, I have this javascript.
<script type="text/javascript">
function pageLoad(sender, args) {
InitLocationsAutoComplete();
}
</script>
<asp:UpdatePanel ID="upScript" runat="server">
<ContentTemplate>
<script type="text/javascript">
function InitLocationsAutoComplete() {
var locationsJson = '<%= LocationOptions %>';
alert(locationsJson);
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
I'm setting a breakpoint on my getter and setter in the C# code.
I'm using MVP and the setter gets called from a presenter.
On first page load, things work as expected. The breakpoint on the setter gets hit first. Then the breakpoint on the getter. Finally, I get a javascript alert with the value I expect to see.
I'm running into problems on partial postbacks that are triggered by other update panels. On those, my setter breakpoint hits with a new value. My getter breakpoint gets hit next, and if I quick watch Session["LocationOptions"] I see the new value there. But when I get the javascript alert, it still alerts the initial value from the first page load.
If it still calls the property in C#, then I don't see why the updated value doesn't come through to the javascript. Why am I stuck with the initial value from first page load?

As far as I know, javascript in the partially updated content is not re-executed/re-evaluated. My understanding is that the partial update will essentially edit the DOM to update a part of the page, but this does not allow one to dynamically upate javascript on the page. You can use ScriptManager.RegisterClientScriptBlock on the server-side to register your updated javascript during the partial postback.

I've had the same issue in the past.
The issue is due to the fact that the dom is only partially updated, i've personally corrected this by registering the script in the ScriptManager.
An example of this is here: ScriptManager.RegisterClientScriptBlock Method (Control, Type, String, String, Boolean)
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_PreRender(object sender, EventArgs e)
{
string script = #"
function ToggleItem(id)
{
var elem = $get('div'+id);
if (elem)
{
if (elem.style.display != 'block')
{
elem.style.display = 'block';
elem.style.visibility = 'visible';
}
else
{
elem.style.display = 'none';
elem.style.visibility = 'hidden';
}
}
}
";
ScriptManager.RegisterClientScriptBlock(
this,
typeof(Page),
"ToggleScript",
script,
true);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>ScriptManager RegisterClientScriptInclude</title>
</head>
<body>
<form id="Form1" runat="server">
<div>
<br />
<asp:ScriptManager ID="ScriptManager1"
EnablePartialRendering="true"
runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1"
UpdateMode="Conditional"
runat="server">
<ContentTemplate>
<asp:XmlDataSource ID="XmlDataSource1"
DataFile="~/App_Data/Contacts.xml"
XPath="Contacts/Contact"
runat="server"/>
<asp:DataList ID="DataList1" DataSourceID="XmlDataSource1"
BackColor="White" BorderColor="#E7E7FF" BorderStyle="None"
BorderWidth="1px" CellPadding="3" GridLines="Horizontal"
runat="server">
<ItemTemplate>
<div style="font-size:larger; font-weight:bold; cursor:pointer;"
onclick='ToggleItem(<%# Eval("ID") %>);'>
<span><%# Eval("Name") %></span>
</div>
<div id='div<%# Eval("ID") %>'
style="display: block; visibility: visible;">
<span><%# Eval("Company") %></span>
<br />
<a href='<%# Eval("URL") %>'
target="_blank"
title='<%# Eval("Name", "Link to the {0} Web site") %>'>
<%# Eval("URL") %></a>
</asp:LinkButton>
<hr />
</div>
</ItemTemplate>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<SelectedItemStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<AlternatingItemStyle BackColor="#F7F7F7" />
<ItemStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
</asp:DataList>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
i hope this helps.

Related

Dropdownlist inside Updatepanel not passing selected item

I have a Gridview that has a hide/show panel. Inside the Panel there is a dropdown and a button. On button press I need the selected value of the dropdown, but I keep getting the first item, no matted what is selected.
I have been investigating the issue and it is to do with the panel control. If I place the dropdown outside the panel, everything works as intended. But dropdown only passes the first value when inside the panel.
Here is my code:
ASP Code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="DD.aspx.cs" Inherits="DD" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<title></title>
<script type="text/javascript">
$(document).on("click", '[src*=plus]', function () {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "images/minus.png");
});
$(document).on("click", '[src*=minus]', function () {
$(this).attr("src", "images/plus.png");
$(this).closest("tr").next().remove();
})
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:constr %>" SelectCommand="SELECT * FROM [Requests]"></asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:constr %>" SelectCommand="SELECT [Name] FROM [Staff]"></asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="RequestID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="RequestID" HeaderText="RequestID" InsertVisible="False" ReadOnly="True" SortExpression="RequestID" />
<asp:TemplateField>
<ItemTemplate>
<img runat="server" style="cursor: pointer" src="images/plus.png" />
<asp:UpdatePanel ID="pnlOrders" runat="server" Style="display: none" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" DataTextField="Name" DataValueField="Name" AutoPostBack="true">
</asp:DropDownList>
<asp:Button runat="server" ID="test" OnClick="test_Click" />
</ContentTemplate> </asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
C# Code
protected void test_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
DropDownList referalDD = gvr.FindControl("DD1") as DropDownList;
string www = referalDD.SelectedItem.Text;
string qqq = referalDD.SelectedItem.Value;
}
Can anyone help me to solve this issue
Ok so I have found a work around / solution. Thanks to Niko for the placeholder suggestion. I got rid of this code:
<img runat="server" style="cursor: pointer" src="images/plus.png" />
and the related Jquery
$(document).on("click", '[src*=plus]', function () {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "images/minus.png");
});
$(document).on("click", '[src*=minus]', function () {
$(this).attr("src", "images/plus.png");
$(this).closest("tr").next().remove();
})
Added a placeholder around the updatepanel and a Image button
<asp:ImageButton runat="server" ID="ShowHide" ImageUrl="~/images/plus.png" OnClick="ShowHide_Click" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible="false">
And this code for the button click event.
protected void ShowHide_Click(object sender, EventArgs e)
{
ImageButton btn = (ImageButton)sender;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
PlaceHolder ph = gvr.FindControl("PlaceHolder1") as PlaceHolder;
if (btn.ImageUrl.ToString() == "~/images/plus.png")
{
ph.Visible = true;
btn.ImageUrl = "~/images/minus.png";
}
else
{
ph.Visible = false;
btn.ImageUrl = "~/images/plus.png";
}
}
Note: After further testing the whole issue was to do with UpdatePanel having this code Style="display: none" As soon as I removed this, everything worked. But I added the placeholder for by show/Hide feature.

checkbox autopostback without refreshing page asp net

I have this checkbox that I need to be AutoPostBack="True" so that I can trigger OnCheckedChanged="chkCompany_OnCheckedChanged". The problem is that I dont want the page to be refreshed and redirected, I want the user to stay put exactly where they are.
ASPX:
<asp:CheckBox OnCheckedChanged="chkCompany_OnCheckedChanged" AutoPostBack="True" CssClass="chkCompany" ClientIDMode="Static" ID="chkCompany" runat="server" />
C#:
protected void chkCompany_OnCheckedChanged(object sender, EventArgs e)
{
if (chkCompany.Checked)
{
txtName.Visible = false;
}
else
{
txtName.Visible = true;
}
}
You should use UpdatePanel control to do this
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:CheckBox OnCheckedChanged="chkCompany_OnCheckedChanged" AutoPostBack="True" CssClass="chkCompany" ClientIDMode="Static" ID="chkCompany" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
Keep your code inside update pannel.
you can use javascript to do this,if Update panel does not work.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script type=text/javascript>
function CheckedChanged()
{
if((document.getElementById('chkCompany').checked))
`{`
document.getElementById('txtname').Visible=false;
}
`else`
{
document.getElementById('txtname').Visible=false;
`}`
}
</script>
</head>
<body>
<asp:CheckBox OnCheckedChanged="CheckedChanged" AutoPostBack="false" CssClass="chkCompany" ClientIDMode="Static" ID="chkCompany" runat="server" />
<asp:TextBox ID="txtname" runat="server"/>
</body>
</html>
-----------------------------------------------------------------------------
Here is another solution but for DropDownCheckList.
The same works for CheckBox.
<asp:UpdatePanel runat="server">
<ContentTemplate>
<cwc:DropDownCheckList runat="server" ID="myId" AutoPostBack="True" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="myId" />
</Triggers>
</asp:UpdatePanel>

Only allow one checkbox to be selected in gridview within modalpopup

I have a modal popup that has a gridview, this gridview has a number of rows, I only want the user to be able to select one row. So if they select another it will deselect the previous one.
I have tried a number of methods but can't get the oncheckedchanged event to fire.
Please can someone assist
Cheers
<asp:button id="btnShowPopupOW" style="display: none" runat="server" />
<asp:modalpopupextender id="mpeOW" behaviorid="mpeOW" runat="server" targetcontrolid="btnShowPopupOW"
popupcontrolid="pnlpopupOW" cancelcontrolid="imgOWCancel" backgroundcssclass="modalBackground" />
<asp:panel id="pnlpopupOW" runat="server" width="600px" style="display: none;" class="ModalPanel">
<div style="position: relative; min-height: 490px;">
<asp:UpdatePanel ID="upExisting" runat="server" ChildrenAsTriggers="true">
<ContentTemplate>
<table style="width: 600px;">
<tr height="25px">
<td>
<asp:Panel ID="pnlPrev" runat="server" Height="200px" ScrollBars="Auto" HorizontalAlign="Center">
<asp:GridView ID="grdPrevious" runat="server" ClientIDMode="Static" AutoGenerateColumns="false" Width="100%"
ShowFooter="false" ShowHeaderWhenEmpty="false" DataKeyNames="ID" >
<Columns>
<asp:BoundField DataField="dates" HeaderText="Dates" />
<asp:BoundField DataField="Prev" HeaderText="Previous" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="ChkSelect" runat="server" OnCheckedChanged="ChkSelect_OnCheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</td>
</tr>
</table>
</ContentTemplate>
<Triggers>
</Triggers>
</asp:UpdatePanel>
</div>
</asp:panel>
with the following in the codebehind
protected void ChkSelect_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox activeCheckBox = sender as CheckBox;
foreach (GridViewRow rw in grdPrevious.Rows)
{
CheckBox chkBx = (CheckBox)rw.FindControl("ChkSelect");
if (chkBx != activeCheckBox)
{
chkBx.Checked = false;
}
else
{
chkBx.Checked = true;
}
}
}
You can do it like this. With single check box selection using jquery....
<ItemTemplate>
<asp:CheckBox ID="ChkSelect" runat="server" onclick="CheckOne(this)" />
</ItemTemplate>
function CheckOne(obj) {
var grid = obj.parentNode.parentNode.parentNode;
var inputs = grid.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
if (obj.checked && inputs[i] != obj && inputs[i].checked) {
inputs[i].checked = false;
}
}
}
}
you want to a single checked in check box . i think Using this you will be able to select only one check box at a time. Put the following java script code in the head section of the web page
<script type="text/javascript">
function SingleCheckboxCheck(ob)
{
var gridvalue = ob.parentNode.parentNode.parentNode;
var inputs = gridvalue.getElementsByTagName("input");
for(var i=0;i<inputs.length;i++)
{
if (inputs[i].type =="checkbox")
{
if(ob.checked && inputs[i] != ob && inputs[i].checked)
{
inputs[i].checked = false;
}
}
}
}
</script>
Here checkbox as a TemplateField of the GridView inside just call the above javascript function to make it single checkable.
onclick ="SingleCheckboxCheck(this)"
What you need is probably a (RadioButton)[http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.radiobutton(v=vs.110).aspx] instead of a CheckBox.
You can group the RadioButton's together which then allows the user to only select one item and automatically deselects the previous selected - or: exactly the behavior you want for your application.
This example code is taken from the linked MSDN Documentation. Note the GroupName attribute
<%# Page Language="C#" AutoEventWireup="True" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>RadioButton Example</title>
<script language="C#" runat="server">
void SubmitBtn_Click(Object Sender, EventArgs e) {
if (Radio1.Checked) {
Label1.Text = "You selected " + Radio1.Text;
}
else if (Radio2.Checked) {
Label1.Text = "You selected " + Radio2.Text;
}
else if (Radio3.Checked) {
Label1.Text = "You selected " + Radio3.Text;
}
}
</script>
</head>
<body>
<h3>RadioButton Example</h3>
<form id="form1" runat="server">
<h4>Select the type of installation you want to perform:</h4>
<asp:RadioButton id="Radio1" Text="Typical" Checked="True" GroupName="RadioGroup1" runat="server" />
<br />
This option installs the features most typically used. <i>Requires 1.2 MB disk space.</i><br />
<asp:RadioButton id="Radio2" Text="Compact" GroupName="RadioGroup1" runat="server"/>
<br />
This option installs the minimum files required to run the product. <i>Requires 350 KB disk space.</i>
<br />
<asp:RadioButton id="Radio3" runat="server" Text="Full" GroupName="RadioGroup1" />
<br />
This option installs all features for the product. <i>Requires 4.3 MB disk space.</i>
<br />
<asp:button text="Submit" OnClick="SubmitBtn_Click" runat="server"/>
<asp:Label id="Label1" font-bold="true" runat="server" />
</form>

asp ModalPopupExtender is getting closed when page is getting postback

I am using asp ModalPopupExtender to display a treeview in asp.net page. When I click a button a ModalPopupExtender will be raised and loads the treeview with checkbox( loading treeview is a usercontrol ascx). In that usercontrol I have written some server side code for when I check a parent node all the child nodes should be checked. Fot this my page will get postback. My problem is when my page gets post back my ModalPopupExtender is getting off and on and my functions are working fine.
here is my treeview in ascx page
<asp:TreeView ID="tvFolderSelect" runat="server" RootNodeStyle-ForeColor="Black"
CssClass="foldertree" LeafNodeStyle-ForeColor="Black" LeafNodeStyle-Font-Bold="false"
ParentNodeStyle-ForeColor="Black" Width="100%" Style="margin: 3px 0 0 -16px;"
OnTreeNodePopulate="tvFolderSelect_TreeNodePopulate" OnTreeNodeCheckChanged="tvFolderSelect_TreeNodeCheckChanged" onclick="postbackOnCheck(event);"
ShowCheckBoxes="All" >
<LeafNodeStyle Font-Bold="False" ForeColor="Black" CssClass="foldertreeleafnode"
ImageUrl="~/images/img_dms/sm_fldr.png" />
<ParentNodeStyle Font-Italic="True" ImageUrl="~/images/img_dms/sm_fldr.png" Font-Underline="True"
CssClass="foldertreeparentnode"/>
<NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black" HorizontalPadding="0px"
NodeSpacing="0px" VerticalPadding="0px" />
<RootNodeStyle ForeColor="Black" CssClass="foldertreerootnode" />
<SelectedNodeStyle Font-Underline="False" HorizontalPadding="0px" VerticalPadding="0px" />
</asp:TreeView>
and here is the javascript function to get postback
function postbackOnCheck(e) {
var evt = e || window.event;
var o = evt.target || evt.srcElement;
if (o.tagName == 'INPUT' && o.type == 'checkbox' && o.name != null && o.name.indexOf('CheckBox') > -1) {
__doPostBack("", "");
}
}
Here is I am using the control
<img id="AddActivity" runat="server" src="../images/plus1.gif" alt="" style="text-align: right;
cursor: pointer; float: right; padding: 1%;" />
<asp:ModalPopupExtender ID="MPEACT" runat="server" TargetControlID="AddActivity"
PopupControlID="ACTDiv" BackgroundCssClass="modalBackground" />
How can I stop getting invisibility of the ajax popup.
here is what I did to re-create your issue. I've created a web page with a modal popup extender.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ModalPopExample.aspx.cs" Inherits="WebApp.ModalPopup.ModalPopExample" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test Page</title>
<style type="text/css">
.hide
{
display:block;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</ajaxToolkit:ToolkitScriptManager>
<asp:Panel ID="Panel1" CssClass="hide" runat="server" BorderColor="Red" BorderStyle="Dashed" BorderWidth="3px">
Are you sure?
<br />
<asp:Button ID="btnok" runat="server" Text="OK" />
<asp:Button ID="btncancel" runat="server" Text="Cancel" />
</asp:Panel>
<asp:Button ID="btnShow" runat="server" Text="Show Modal" />
<asp:Image ID="Image1" ImageUrl="~/image_loader.ashx" runat="server" />
<ajaxToolkit:ModalPopupExtender ID="btnShow_ModalPopupExtender" DropShadow="true" OkControlID="btnok" CancelControlID="btncancel" PopupControlID="Panel1" runat="server" DynamicServicePath="" Enabled="True" TargetControlID="btnShow">
</ajaxToolkit:ModalPopupExtender>
</form>
<script>
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(function () {
console.log('loaded');
});
</script>
</body>
</html>
Notice that the image is loaded via a handler file (ashx):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
namespace WebApp.ModalPopup
{
/// <summary>
/// Summary description for image_loader
/// </summary>
public class image_loader : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpg";
var imagePath = context.Server.MapPath("~/images/windows_xp_bliss-wide.jpg");
Thread.Sleep(20000);
context.Response.TransmitFile(imagePath);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
The popup flickers for a while. The most simple workaround you can do is hide the element at first itself (via css) and some javascript is required to remove that css when the web page if fully loaded.
<style type="text/css">
.hide
{
display:none;
}
</style>
When you ajax client scripts all finish loading...find the control and remove the above class on the element.
<script>
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(function () {
console.log('loaded');
var div = document.getElementById('Panel1');
div.className = '';
});
</script>
Hope this helps.
Try to use update panel and refer below link for detail why Modalpopup close on postback?
http://patelshailesh.com/index.php/why-does-modalpopup-close-on-postback
You can use this JavaScript function on button click:
<script>
$("#btn").click(
function () {
window.top.location = "WebForm1.aspx";
});
</script>
I had used this function to auto update a grid on closing the Popup, if you want to see that Article and want to see how I had used this function then you can refer to this link:
http://www.c-sharpcorner.com/UploadFile/cd7c2e/how-to-auto-refresh-grid-view-on-closing-of-popup-menu/
Many other Articles and similar forums can be found on http://www.c-sharpcorner.com/
I used AsyncPostBackTrigger to run the server side code and changed the __DoPostBack method parameters. now my treeview design is
<div id="form" runat="server">
<asp:UpdatePanel ID="updTree" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TreeView ID="tvFolderSelect" runat="server" RootNodeStyle-ForeColor="Black"
CssClass="foldertree" LeafNodeStyle-ForeColor="Black" LeafNodeStyle-Font-Bold="false"
ParentNodeStyle-ForeColor="Black" Width="100%" Style="margin: 3px 0 0 -16px;"
OnTreeNodePopulate="tvFolderSelect_TreeNodePopulate" OnTreeNodeCheckChanged="tvFolderSelect_TreeNodeCheckChanged"
ShowCheckBoxes="All" onclick="postbackOnCheck(event);">
<LeafNodeStyle Font-Bold="False" ForeColor="Black" CssClass="foldertreeleafnode"
ImageUrl="~/images/img_dms/sm_fldr.png" />
<ParentNodeStyle Font-Italic="True" ImageUrl="~/images/img_dms/sm_fldr.png" Font-Underline="True"
CssClass="foldertreeparentnode" />
<NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black" HorizontalPadding="0px"
NodeSpacing="0px" VerticalPadding="0px" />
<RootNodeStyle ForeColor="Black" CssClass="foldertreerootnode" />
<SelectedNodeStyle Font-Underline="False" HorizontalPadding="0px" VerticalPadding="0px" />
</asp:TreeView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="tvFolderSelect" EventName="TreeNodeCheckChanged" />
</Triggers>
</asp:UpdatePanel>
and the function to postback is
function postbackOnCheck(e) {
var evt = e || window.event;
var o = evt.target || evt.srcElement;
if (o.tagName == 'INPUT' && o.type == 'checkbox' && o.name != null && o.name.indexOf('CheckBox') > -1) {
__doPostBack('<%=updTree.ClientID %>', 'Refresh:0,1,2');
}
}
Now my panel is not closing while getting postback

How to Hide error message of a asp custom validator

I am using asp requiredfieldvalidator. I want the required field validator to fire only when a checkbox on my form is checked.
When the checkbox is fired, the validator works as expected and error message shows up but when the checkbox is unchecked the errormessage that showed up stays on the screen. I have tried different options like validator.resetForm(); disabling the validator, hiding the validator but the error message stays on the screen form. Here is the simplified version of my code:
<script src="jquery-1.4.2.min.js"></script>
<!DOCTYPE html>
<script type="text/javascript">
function enableDisableControls(value) {
var enabledSilentPost = $("#<%=chkEnableSilentPost.ClientID%>").attr("checked");
var validatorControl = $("#<%=valApprovalURL.ClientID%>")[0];
ValidatorEnable(validatorControl, enabledSilentPost);
// If the checkbox is false then assume that the
if (!enabledSilentPost) {
validatorControl.enabled = false;
}
}
$(document).ready(function () {
$("#<%=chkEnableSilentPost.ClientID%>").click(function () {
enableDisableControls();
});
enableDisableControls();
});
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div>
<asp:CheckBox ID="chkEnableSilentPost" runat="server" Width="250px" Text="Enable" />
<asp:Label ID="lblApprovalURL" runat="server" Text="URL" CssClass="controllabel" meta:resourcekey="lblApprovalURLResource"></asp:Label>
<asp:TextBox ID="txtApprovalURL" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="valApprovalURL" runat="server" ControlToValidate="txtApprovalURL" ErrorMessage="Please enter Valid Text" Text="*"></asp:RequiredFieldValidator>
<actk:ValidatorCalloutExtender ID="extApprovalURL" TargetControlID="valApprovalURL" runat="server" Enabled="True"></actk:ValidatorCalloutExtender>
</div>
</form>
I am was able to get the validators to react by doing the following. The Validator was pretty simpe, but I had to predict the ID of the Extender in order for it to work:
<script type="text/javascript">
$(function () {
$('#<%=chkEnableSilentPost.ClientID %>').click(function () {
$("#<%=valApprovalURL.ClientID %>").toggle(this.checked);
$("#extApprovalURL_popupTable").toggle(this.checked);
});
});
</script>
<form id="form1" runat="server">
<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" />
<div>
<asp:CheckBox ID="chkEnableSilentPost" runat="server" Width="250px" Text="Enable" />
<asp:Label ID="lblApprovalURL" runat="server" Text="URL" CssClass="controllabel" meta:resourcekey="lblApprovalURLResource"></asp:Label>
<asp:TextBox ID="txtApprovalURL" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="valApprovalURL" runat="server" ControlToValidate="txtApprovalURL" ErrorMessage="Please enter Valid Text" Text="*"></asp:RequiredFieldValidator>
<asp:ValidatorCalloutExtender ID="extApprovalURL" TargetControlID="valApprovalURL" runat="server" Enabled="True"></asp:ValidatorCalloutExtender>
</div>
</form>

Categories

Resources