Visibility turns to none after postback automatically - c#

I tried to make the visibility of a div through javascript.
<asp:LinkButton class="ProfilePageDetailLinks" ID="lbtnPersonal" runat="server" OnClientClick="VisibleTab('PersonalDetails')">Show Details</asp:LinkButton>
<div id="PersonalDetails">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
</div>
function VisibleTab(str) {
if (document.getElementById(str).style.display == 'none') {
document.getElementById(str).style.display = 'block';
} else {
document.getElementById(str).style.display = 'none';
}
But after the postback, the div is hiding automatically.
Please check the code below... Its not working as expected.. How to make it works.. Thats my actual doubt...
<form id="form1" runat="server">
<div>
<div runat="server" id='G2'>
content</div>
<asp:Button ID="Button1" OnClientClick="javascript:document.getElementById('G2').style.visibility = 'visible';"
runat="server" Text="show" />
<asp:Button ID="Button2" OnClientClick="javascript:document.getElementById('G2').style.visibility = 'hidden';"
runat="server" Text="hide" />
</div>
</form>

You can add return false; to avoid your postback
OnClientClick="VisibleTab('PersonalDetails'); return false;"

Related

How to close radwindow and response to current page in asp.net?

I want to close radwindow and refresh page. But when I run script, radwindow closed but redirect to hoem page.
<telerik:RadWindow ID="modalPopup" runat="server" ShowContentDuringLoad="true" VisibleStatusbar="false"
RegisterWithScriptManager="True" EnableShadow="True" ReloadOnShow="true" Width="760px"
Height="350px" Modal="True" OpenerElementID="btnAddContact" Skin="WebBlue">
<ContentTemplate>
<asp:UpdatePanel ID="Updatepanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="btnSave" runat="server" CssClass="acceptBTN btn h4" Text="ثبت" OnClick="btnSave_Click" />
<input type="button" value="انصراف" class="cancelBTN btn h4" onclick="CancelClick()" />
</div>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</ContentTemplate>
function CancelClick() {
var wnd = $find("<%=modalPopup.ClientID %>");
wnd.close();
window.parent.location.reload(true);
Sys.Application.remove_load(showDialogInitially);
window.top.location = this;
}
</script>
List.aspx.cs
string strStartUpScript = string.Format("javascript:CancelClick();");
ScriptManager.RegisterStartupScript(Page, GetType(), "PopupScript", strStartUpScript, true);

Asp.NET: How to keep focus on textbox in a nested Update Panel

I am working on making a semi simple post and reply/forum pages in asp.net(with C#). Everything works however when I went to add update panels it makes me want to throw my head into a wall.
I use a DataList to display the posts. I use a form consisting of two textboxes and a button to insert a new post. One textbox if for the name, and the other for the message.
First update panel I added (nested) is to provide a character count for the post. I have a label in the Content and it is triggered by the textboxes textchanged event. The textbox 'txtMessage' also has a java-script function run 'onkeyup' to keep the focus on the textbox when typing. I limit the characters at 1000.
The next update is to surround the DataList so that it does not post back everytime (if not used and the back button is hit it will go back and visually remove each post which is not a good design practice). However when I just put the panel around the DataList it did not postback the insert form so the boxes were not cleared. Which I would like to be done, so I wrapped everything then by this updatepanel, which then made the character count update panel nested by this one. This now works, but the focus is taken off of the txtMessage box each time the textchanged event fires. So the JavaScript is not firing now?
I have moved the opening and closing of the update panel countless times and have tried different fixes, so any further suggestions would help. The code is below.
ForumT.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ForumT.aspx.cs" Inherits="UPE_Site_v1.ForumT" %>
<asp:Content ID="Content1" ContentPlaceHolderID="title" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="headPlaceHolder" runat="server">
<script type="text/javascript">
function reFocus(id) {
__doPostBack(id, '');
document.getElementById(id).blur();
document.getElementById(id).focus();
}
</script>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="contentPlaceHolder" runat="server">
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetPosts" TypeName="TimeTrackerRepository" DataObjectTypeName="System.Guid" DeleteMethod="DeletePost"> </asp:ObjectDataSource>
<asp:UpdatePanel ID="upDataList" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div>
<asp:DataList ID="DataList2" runat="server" CellPadding="4" DataSourceID="ObjectDataSource1"
ForeColor="#333333" OnItemCommand="DataList2_ItemCommand" OnItemDataBound="DataList2_ItemDataBound"
DataKeyField="PostID" OnItemCreated="DataList2_ItemCreated">
<AlternatingItemStyle BackColor="White" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<ItemStyle BackColor="#D4EBD4" />
<ItemTemplate>
<div class="row">
<div class="col-xs-12 col-sm-6">
Name: <strong><%# Eval("Name") %></strong>
</div>
<div class="col-xs-12 col-sm-6">
<%# Eval("TimePosted") %>
</div>
<div class="col-xs-12" style="word-break: break-all">
<%# Eval("Message") %>
</div>
</div>
<br />
<asp:Button ID="btnDelete" CssClass="btn btn-warning" runat="server" Text="Delete" CommandArgument='<%# Eval("PostID") %>' CommandName="DeleteItem" />
<asp:LinkButton CssClass="btn btn-primary" ID="lkbtnFullPost" runat="server" Text="See Full Post" CommandArgument='<%# Eval("PostID") %>' CommandName="FullPost"></asp:LinkButton>
</ItemTemplate>
<SelectedItemStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
</asp:DataList>
</div>
<%--</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnPost" EventName="Click" />
</Triggers>
</asp:UpdatePanel>--%>
<br />
<br />
<div class="row">
<div class="col-xs-12 col-sm-10 col-md-8 col-lg-6 col-sm-offset-1 col-md-offset-2 col-lg-offset-3">
<p>Add a post to this forum:</p>
<div class="form-group">
<asp:Label ID="Label1" runat="server" Text="Name: "></asp:Label>
<asp:TextBox CssClass="form-control" ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtName"
ErrorMessage="This is a required field." ValidationGroup="Application"
Display="Dynamic" ForeColor="Red">
</asp:RequiredFieldValidator>
</div>
<%--<asp:UpdatePanel ID="upMessage" runat="server" UpdateMode="Conditional">
<ContentTemplate>--%>
<div class="form-group">
<asp:Label ID="Label2" runat="server" Text="Message: "> </asp:Label>
<asp:TextBox onkeyup="reFocus(this.id);" CssClass="form-control" ID="txtMessage" runat="server" TextMode="MultiLine" Rows="4" OnTextChanged="txtMessage_TextChanged"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtMessage"
ErrorMessage="This is a required field." ValidationGroup="Application"
Display="Dynamic" ForeColor="Red">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator runat="server" ControlToValidate="txtMessage"
ErrorMessage="Character limit is 1000 characters."
ValidationGroup="Application" Display="Dynamic" ForeColor="Red"
ValidationExpression=".{0,1000}">
</asp:RegularExpressionValidator>
</div>
<br />
<%--</div>
</div>--%>
<%--</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnPost" EventName="Click" />
</Triggers>
</asp:UpdatePanel>--%>
<%--<div class="row">
<div class="col-xs-12 col-sm-10 col-md-8 col-lg-6 col-sm-offset-1 col-md-offset-2 col-lg-offset-3">--%>
<asp:UpdatePanel ID="upMessage" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblCharacterCount" runat="server">0/1000</asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtMessage" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ValidationGroup="Application" CssClass="btn btn-default" ID="btnPost" runat="server" Text="POST IT" OnClick="btnPost_Click" />
<asp:Label ID="lblError" runat="server" Text="" CssClas="Error" ForeColor="Red"></asp:Label>
</div>
</div>
<br />
<br />
<br />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
ForumT.aspx.cs
only including the textchanged event
protected void txtMessage_TextChanged(object sender, EventArgs e)
{
lblCharacterCount.Text = txtMessage.Text.Count().ToString() + "/1000";
if (txtMessage.Text.Count() >= 1000)
{
lblCharacterCount.ForeColor = System.Drawing.Color.Red;
}
else
{
lblCharacterCount.ForeColor = System.Drawing.Color.Black;
}
}
Sorry for the code being a little sloppy. Also side not, I am using bootstrap so that is what all of the div's are for
I was facing the same issue as I needed to set focus on the textbox after postbacks in update panel. So I researched over internet & found this Javascript code. I tried it & it is working perfectly. It adds event listener for update panel for before & after postback. Gets textbox id before postback & set it after completion of postback.
var lastFocusedControlId = "";
function focusHandler(e) {
document.activeElement = e.originalTarget;
}
function appInit() {
if (typeof (window.addEventListener) !== "undefined") {
window.addEventListener("focus", focusHandler, true);
}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoadingHandler);
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);
}
function pageLoadingHandler(sender, args) {
lastFocusedControlId = typeof (document.activeElement) === "undefined"
? "" : document.activeElement.id;
}
function focusControl(targetControl) {
if (Sys.Browser.agent === Sys.Browser.InternetExplorer) {
var focusTarget = targetControl;
if (focusTarget && (typeof (focusTarget.contentEditable) !== "undefined")) {
oldContentEditableSetting = focusTarget.contentEditable;
focusTarget.contentEditable = false;
}
else {
focusTarget = null;
}
targetControl.focus();
if (focusTarget) {
focusTarget.contentEditable = oldContentEditableSetting;
}
}
else {
targetControl.focus();
}
}
function pageLoadedHandler(sender, args) {
if (typeof (lastFocusedControlId) !== "undefined" && lastFocusedControlId != "") {
var newFocused = $get(lastFocusedControlId);
if (newFocused) {
focusControl(newFocused);
}
}
}
Sys.Application.add_init(appInit);
Just use this code in your script on aspx page.
You say your javascript is not working. When using update panels and js you will need to rebind your js subscribed events.
Reference: jQuery $(document).ready and UpdatePanels?

Calling a method from a AsyncFileUpload's UploadedComplete isn't working as expected

I have an AsyncFileUpload control that should show a panel and set some text when the upload completes successfully. When I debug it, the event fires and I see that the method is called correctly, but the form doesn't update.
Here's the markup:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="well well-large">
<form class="navbar-form pull-left">
<ajaxToolkit:AsyncFileUpload runat="server" class="search-query" ID="AsyncFileUpload" Width="400px"
UploadingBackColor="AppWorkspace" ThrobberID="myThrobber" CompleteBackColor="#068712" OnUploadedComplete="AsyncFileUpload_UploadedComplete" />
<br />
</form>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="AsyncFileUpload" EventName="UploadedComplete" />
</Triggers>
</asp:UpdatePanel>
<asp:UpdatePanel ID="panAlertUpdatePanel" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Panel runat="server" ID="panAlert" Visible="false">
<div class="alert alert-success" id="divAlert" runat="server">
<button id="Button1" runat="server" type="button" class="close" data-dismiss="alert">×</button>
You shouldn't see this message!
</div>
<asp:Panel runat="server" ID="panMarquee" Visible="true">
<div id="Div1" runat="server" class="progress progress-success progress-striped">
<div id="ProgressBar" runat="server" class="bar" style="width: 100%"></div>
</div>
</asp:Panel>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
And here's the server code:
protected void AsyncFileUpload_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
if (AsyncFileUpload.HasFile)
{
this.SetMessage(Message.Success);
}
else
{
this.SetMessage(Message.Fail);
}
}
#endregion
#region Miscellaneous
private enum Message { Success, Fail }
private void SetMessage(Message msg)
{
if (msg == Message.Success)
{
this.divAlert.InnerText = "Well done! The document appears to have uploaded successfully. Please wait...";
this.divAlert.Attributes.Add("class", "alert alert-success");
}
else
{
this.divAlert.InnerText = "Oh snap! Something broke. Please contact IT right away.";
this.divAlert.Attributes.Add("class", "alert alert-error");
}
this.panAlert.Visible = true;
this.panAlertUpdatePanel.Update();
}
It was working just fine when I was using a button as the trigger, but not when I changed it to just the AsyncFileUpload control.
Any ideas?

How to refresh a single item inside Repeater control using updatepanel

I'm making a social network website, the problem I'm facing here is that I used an update panel inside the repeater and I want to refresh the contents of the updatepanel when the user clicks on any linkbutton and ofcourse this updatepanel will be repeated foreach (div-post), but when I click on any linkbutton inside the repeater control and the updatepanel it doesn't refresh. How do I force it to refresh ?. Here is the code I'm using ...
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Repeater ID="Repeater1" runat="server"
OnItemCommand="MyButtonCommandEvent">
<ItemTemplate>
<asp:UpdatePanel ID="UpdatePanel3" runat="server">
<ContentTemplate>
<div class="post">
<asp:HiddenField ID="postID_hidden" runat="server"
Value='<%# Eval("posts_ID") %>' />
<div class="Thumb">
<img src="thumbs/abdo_thumb.jpg"> </img></div>
<span class="user"><%#Eval("poster_name")%>
</span>
<div class="post-body">
<p>
<%#Eval("description")%>
</p>
</div>
<div class="post-options" style=" height:22px; ">
<span class="first"><%#Eval("post_date")%></span>
<ul style="display:inline; list-style-type: none;">
<li>
<div class="tooltip">
Comments
<img class="tool-img" src="Images/comments.png"> : <%#Eval("comment_num") %>
</img>
</div>
</li>
<li>
<div class="tooltip">
<asp:LinkButton ID="like_linkbtn" runat="server" CommandName="Like" OnClick="Like_Click"><%#(Eval("name_like").ToString() == "") ? "Like" : Eval("name_like")%></asp:LinkButton>
<img class="tool-img" src="images/likes.png"> : <%#Eval("like_counter") %>
</img></div>
</li>
<li>
<div class="tooltip">
<asp:LinkButton ID="hate_linkbtn" runat="server" CommandName="Hate"><%#(Eval("name_hate").ToString() == "") ? "Hate" : Eval("name_hate")%></asp:LinkButton>
<img class="tool-img" src="images/hate.png"> : <%#Eval("hate_counter") %>
</img></div>
</li>
</ul>
</div>
<div class="finish">
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:Repeater>
And the server side code
protected void Like_Click(object sender, EventArgs e)
{
LinkButton1.Text = DateTime.Now.ToString();
}
protected void MyButtonCommandEvent(object source, RepeaterCommandEventArgs e)
{
var postID = e.Item.FindControl("postID_hidden") as HiddenField;
NewUser user = new NewUser();
if (e.CommandName == "Like")
{
user.like_post(int.Parse(postID.Value), (int)Session["accountID"]);
}
else
{
if (e.CommandName == "Hate")
{
user.hate_post(int.Parse(postID.Value), (int)Session["accountID"]);
}
}
// repeater_databind();//This will refresh all the contents of the repeater(bad way)
}
So as can see databind is not working for me because I want to refresh only one item in the repeater control and not the whole items, can anyone help me please ?
Edit :
Problem solved by wrapping the whole repeater in another updatepanel and setting the trigger like this
<asp:UpdatePanel ID="UpdatePanel4" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="false">
<ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Repeater1" EventName="MyButtonCommandEvent" />
</Triggers>
You should try to set the UpdateMode propery of your update panel to Conditional

Passing Control's Value to Modal Popup

Just would like know how to pass textbox value to a modal popup after clicking a button using ModalPopUpExtender in ASP.NET, I've tried these codes but seems that I have no luck :(
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Button1.Attributes.Add("onclick", "showModalPopup(); return false;");
}
</script>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick='showModalPopup(); return false;' />
<cc1:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="Button1"
PopupControlID="Panel1" CancelControlID="btnCancel" OkControlID="btnOkay" BackgroundCssClass="ModalPopupBG">
</cc1:ModalPopupExtender>
<asp:Panel ID="Panel1" Style="display: none" runat="server">
<div class="HellowWorldPopup">
<div class="PopupHeader" id="PopupHeader">
Header</div>
<div class="PopupBody">
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
<div class="Controls">
<input id="btnOkay" type="button" value="Done" />
<input id="btnCancel" type="button" value="Cancel" />
</div>
</div>
</asp:Panel>
javascript
function showModalPopup() {
//show the ModalPopupExtender
var value;
value = document.getElementById("TextBox1").value;
$get("<%=Label1.ClientID %>").value = value;
$find("<%=ModalPopupExtender1.ClientID %>").show();
}
I wonder what I miss out :(, Thanks and I hope someone could help me :)
use
value = document.getElementById('<%=TextBox1.ClientID %>').value;
instead of
value = document.getElementById("TextBox1").value;

Categories