How to hide a column inside a repeater when checkbox is checked? - c#

What I am trying to do is access a column (which has the header title "Add to Shopping List") inside a repeater (areaRepeater) that is inside another repeater (locationRepeater). I want to hide it if a checkbox is checked. However, despite how things are setup, the column is never hidden. I'm not sure what I'm missing here...or maybe I'm going about it the wrong way?
Here is the piece of code that I am trying to use to hide the column in the areaRepeater table. I can hide the submitBtn button successfully, but that button is not inside a repeater.
Sitecore.Data.Fields.CheckboxField checkBox = ProductGroup.Fields["Shopping Disabled"];
if (checkBox.Checked)
{
submitBtn.Visible = false;
Repeater rpt1 = (Repeater)FindControl("locationRepeater");
Response.Write("a ");
foreach (RepeaterItem rep in rpt1.Items)
{
Response.Write("1 ");
Repeater areaRepeater = (Repeater)rep.FindControl("areaRepeater");
foreach (RepeaterItem areaRep in areaRepeater.Items)
{
Response.Write("2 ");
if (showField() == false)
{
Label lbl1 = (Label)areaRep.FindControl("litCol");
CheckBox check = (CheckBox)areaRep.FindControl("LineQuantity");
lbl1.Visible = false;
check.Visible = false;
}
}
}
}
This is the designer code for both repeaters. I tried setting the visibility of the label for the header and the checkbox with a function called showField() but it is never called, even though it does return the correct bool value:
<asp:Repeater ID="locationRepeater" runat="server" OnItemDataBound="SetInner">
<ItemTemplate>
<div class="LocationName">
<%# Eval("SecOpen") %><%# Eval("LocationName")%> <%# Eval("SecClose") %>
</div>
<asp:Repeater ID="areaRepeater" runat="server">
<HeaderTemplate>
<div class="headerRow">
<div class="header">
<div class="thumb"><p></p></div>
<div class="headerField name"><p class="hField">Product</p></div>
<div class="headerField sku"><p class="hField">SKU</p></div>
<div class="headerField size"><p class="hField">Size</p></div>
<div class="headerField case"><p class="hField">Case Pack</p></div>
<div class="headerField use"><p class="hField">Use With</p></div>
<div id="shoppingHeader" class="headerField qty" runat="server"><p class="headerfield qty hField"><asp:Label id="listCol" runat="server" visible='<%# showField() %>' Text="Add To Shopping List" /> </p></div>
</div>
</div>
</HeaderTemplate>
<ItemTemplate>
<asp:placeholder id="LocationAreaHeader" runat="server" visible='<%# (Eval("AreaName").ToString().Length == 0 ? false : true) %>' ><h3> <%# Eval("AreaName") %></h3></asp:placeholder>
<asp:placeholder id="ProductTable" runat="server" visible='<%# (Eval("ProductName").ToString().Length == 0 ? false : true) %>' >
<div class="table">
<div class="row">
<div class="thumb"><%# Eval("Charm") %></div>
<div class="field name"><p class="pField"> <%# Eval("ThumbOpen") %><%# Eval("ProductName") %><%# Eval("ThumbClose") %></p> </div>
<div class="field sku"><p class="pField"> <%# Eval("Sku") %> </p></div>
<div class="field size"><p class="pField"> <%# Eval("Size") %></p></div>
<div class="field case"><p class="pField"> <%# Eval("CasePack") %> </p></div>
<div class="field use"><p class="pField"> <%# Eval("UseWith") %> </p></div>
<div id="shopping" class="field qty" runat="server"><p class="pField"> <asp:checkbox visible='<%# showField() %>' id="LineQuantity" runat="server" /></p></div>
</div>
</div>
<asp:Label id="productID" text='<%# Eval("productID") %>' visible="false" runat="server" />
</asp:placeholder>
<!-- Stored values -->
<asp:Label id="SkuID" runat="server" text='<%# Eval("SkuID") %>' visible="true" />
<asp:Label id="masterSku" runat="server" text='<%# Eval("masterSku") %>' visible="false" />
<asp:Label id="masterName" runat="server" text='<%# Eval("masterName" ) %>' visible="false" />
<asp:Label ID="test" visible="false" runat="server" text='<%# Eval("AreaID") %>' />
</ItemTemplate>
</asp:Repeater>
<asp:Label ID="refID" visible="false" runat="server" text='<%# Eval("LocationID") %>' />
</ItemTemplate>
</asp:Repeater>
This is the showField() function:
protected bool showField()
{
bool retVal = true;
Item CurrentItem = Sitecore.Context.Item;
Item HomeItem = ScHelper.FindAncestor(CurrentItem, "Market");
if (HomeItem != null)
{
Item ProductGroup = HomeItem.Axes.SelectSingleItem(#"child::*[##templatename='MarketOfficeBuildigProductMap']");
if (ProductGroup != null)
{
Sitecore.Data.Fields.CheckboxField checkBox = ProductGroup.Fields["Shopping Disabled"];//curently returns true
ShoppingDisabled.Value = checkBox.Checked.ToString();
if (checkBox.Checked == true)
{
retVal = false;
}
}
}
return retVal;
}

I think you could approach this from a different angle which could make your code a lot simpler.
First off try not to use the OnDataBound event. I prefer to use the DataBinding event for the specific controls as it localizes the code better and you never have search for controls. I am not exactly sure how your code is working but take a look at how I would implement the two controls you are trying to hide to use the DataBinding event.
e.g. for the Checkbox:
<asp:CheckBox id="LineQuantity" runat="server" OnDataBinding="LineQuantity_DataBinding" />
protected void LineQuantity_DataBinding(object sender, System.EventArgs e)
{
CheckBox chk = (CheckBox)sender;
chk.Checked = (bool)(Eval("SomeField")); // Note you can use Eval here...
chk.Visible = showField();
}
This should help you localize the problem at least. I typically use this method of doing any custom work while databinding. The DataBound event is not great because it happens after it is all done. The OnDataBinding event lets you inject whatever type of logic you want at the time the databinding is occurring.

Related

How to update values in a ListView with ajax in asp.net web form

I'm using a listview and ajax in an asp.net web form. In part of that form, I display comments, which readers can rate, either positive or negative.
This value isn't updated unless the page is refreshed, is there a way to update the value without the need of refreshing the page?
<asp:ScriptManager ID="ScriptManager" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel" runat="server">
<ContentTemplate>
<asp:ListView ID="ListView1" runat="server" OnItemCommand="ListView1_ItemCommand">
<ItemTemplate>
<div class="row comm_info_bar ">
<div class="col-md-5 RightDisplay"><%# Eval("name") %></div>
<div class="col-md-5 comm_info_date"><%# Eval("date") %></div>
<asp:LinkButton ID="negBtn" class="glyphicon glyphicon-minus voteCommentIcon voteContNeg text-danger smallGlyph" runat="server" CommandName="negative" CommandArgument='<%#Eval("id")%>' />
<asp:Label ID="lblnegative" name="lblnegative" class=" voteNumNeg" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "negative") %>'></asp:Label>
<asp:LinkButton ID="posBtn" class="glyphicon glyphicon-plus voteCommentIcon voteContNeg text-success smallGlyph" runat="server" CommandName="positive" CommandArgument='<%#Eval("id")%>' />
<asp:Label ID="lblpositive" class="voteNumPos" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "positive") %>'></asp:Label>
</div>
<div class="row">
<div class="col-md-12 comments"><%# Eval("text") %></div>
</div>
</ItemTemplate>
</asp:ListView>
</ContentTemplate>
</asp:UpdatePanel>
and in code:
static List<Int64> commentsUser = new List<long>();
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
string name = e.Item.DataItemIndex.ToString();
long commentId = Convert.ToInt64(e.CommandArgument);
ArticleCommentsDataClass ArticleComment = new ArticleCommentsDataClass();
if (e.CommandName == "positive")
{
if (!searchcomments(commentId))
{
ArticleComment.Comments_positive(commentId);
commentsUser.Add(commentId);
}
}
else
{
if (!searchcomments(commentId))
{
ArticleComment.Comments_negative(commentId);
commentsUser.Add(commentId);
}
}
}
Is there anyone who has an idea on how to do this?
This sounds like you are binding (reading the data of your grid) before executing the command. Since the command changes the data, you should rebind the grid or update it in any other way.
Check out this article that talks about when each event is raised

Repeater Item hides after ItemCommand

Hi I don't know what to title but my problem is that I am showing posts inside a repeater and I have a like button inside it when I press like button, the post hides.
Following is the itemCommand Event.
protected void rptrPosts_ItemCommand(object source, RepeaterCommandEventArgs e)
{
RepeaterItem item = e.Item;
TextBox txtComment = item.FindControl("txtComment") as TextBox;
Label lblID = (Label)item.FindControl("lblID");
LinkButton btnLike = (LinkButton)item.FindControl("btnLike");
int userid = Convert.ToInt32(Session["USERID"]);
int postid = Convert.ToInt32(lblID.Text);
if (e.CommandName == "like")
{
InstagramEntity insta = new InstagramEntity();
int count = (from like in insta.likes where like.like_from == userid & like.like_post== postid select like).Count();
if (count == 0)
{
like lk = new like();
lk.like_from = userid;
lk.like_post = postid;
insta.likes.Add(lk);
insta.SaveChanges();
this.DataBind();
}
}
I also tried rptrposts.DataBind(). PS: I need to referesh the panel after like button is clicked.
Page Load:
if (!IsPostBack)
{
loadpage();
}
LoadPage()
If I remove the (!IsPostBack) condition the item updates, and but doesn't hide but after update, duplicate items are shown.
public void loadpage()
{
InstagramEntity insta = new InstagramEntity();
rptrPosts.DataSource = (from post in insta.posts
join user in insta.users on post.post_by equals user.user_id
orderby post.post_time descending
select new { user.user_name, post.post_time, post.post_image, post.post_caption, post.post_id, post.post_by }).ToList();
rptrPosts.DataBind();
}
Markup:
<asp:Repeater ID="rptrPosts" OnItemCreated="rptrPosts_ItemCreated" OnItemCommand="rptrPosts_ItemCommand" runat="server">
<ItemTemplate>
<div>
<div class="panel panel-default post">
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<div class="panel-heading">
<asp:Label ID="lblID" Visible="false" runat="server" Text='<%# Eval("post_id") %>'></asp:Label>
<img src="Images/homepageimage.jpg" class="img-circle avator" /><a style="margin-left:10px;" href="account.aspx?id=2" ><%# Eval("user_name") %></a><label class="pull-right">Posted On <%# Eval("post_time") %></label>
<asp:HiddenField ID="imagePath" Value='<%# Eval("post_image") %>' runat="server" />
</div>
<div class="panel-body">
<img src='Images/<%# Eval("post_image") %>' class="PostImage img-responsive" />
<div class="well well-sm">
<asp:LinkButton ID="btnLike" CssClass='btn btn-link' CommandName="like" runat="server"><span style="color:red;font-size:x-large" class='<%# getLikeClass(Eval("post_id")) %>'></span></asp:LinkButton><%# getPostlikes(Eval("post_id")) %><br />
<%# Eval("post_caption") %><br />
<ul class="list-group">
<li class="list-group-item"><b>Comments:</b></li>
<asp:LinqDataSource ID="dsComments" runat="server" EnableInsert="true" ContextTypeName="instagram.InstagramEntity" EntityTypeName="" TableName="view_comments" Where="comment_post == #comment_post" OrderBy="comment_time">
<WhereParameters>
<asp:ControlParameter ControlID="lblID" PropertyName="Text" Name="comment_post" Type="Int32"></asp:ControlParameter>
</WhereParameters>
</asp:LinqDataSource>
<asp:Repeater ID="rptrComments" runat="server">
<ItemTemplate>
<li class="list-group-item"><%# Eval("user_name") %> <%# Eval("comment_text") %> </li>
</ItemTemplate>
</asp:Repeater>
</ul>
</div>
</div>
<div class="panel-footer"><asp:LinkButton ID="btnDelete" CssClass="pull-right" Visible='<%# DelVisiblily(Eval("post_by")) %>' CommandName="delete" ToolTip="Delete this Post" runat="server"><span class="glyphicon glyphicon-remove label-danger"></span>Delete</asp:LinkButton> </div>
</div>
</ContentTemplate> </asp:UpdatePanel>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
I am new to asp.net and this is my Semester Project. A help would be nice.
Try loadpage(); instead for this.DataBind(); in rptrPosts_ItemCommand(..);
if (e.CommandName == "like")
{
//code here
if (count == 0)
{
//code here
loadpage();
}
}

ASP.NET button CommandArgument using <% %>

I have the following snippet of code in my .aspx file, I want the button to send the ID to the code behind.
<%List<Notes> CommentsList = FindNotes(ParentNote.ID); %>
<%foreach (var comment in CommentsList) { %>
<div id="note" class="tierTwo"><p><%: comment.Content %></p><ul><li><%: comment.AddedDate %></li><li>20:29</li><li><%: comment.AddedByName %></li><li>Add comment</li></ul> >
<div id="addComment<%:comment.NoteID%>" class="tierOne" style="display:none">
<asp:TextBox ID="commentreplytext" runat="server" rows="4"> </asp:TextBox>
<asp:HiddenField id="ParentIdReply" value='<%=comment.NoteID%>' runat="server" />
<asp:Button ID="Button2" runat="server" Text="Add" CommandArgument="<%: comment.NoteID%>" OnCommand="Add_Comment" />
</div>
</div>
The code behind currently looks like this
protected void Add_Comment(object sender, CommandEventArgs e)
{
string uniqueNoteID = e.CommandArgument.ToString();
}
The command argument is getting sent to the Add_Comment method but it returns "<%: comment.NoteID%>" rather than the value it represents. This way of retrieving the NoteID value works fine when setting the div id so I don't know why it is causing an issue in the commandArgument.
Unfortunately you can't use <%%> code blocks in .NET controls. It's to do with the order things get rendered in. You'll have to set the CommandArgument in the code behind when you build the page. You could do that if you built the page using a repeater rather than a for each in the page.
<asp:Repeater runat="server" id="repeater1">
<ItemTemplate>
<div id="note" class="tierTwo"><p><%# Eval("Content") %></p><ul>
<li><%# Eval("AddedDate") %></li><li>20:29</li>
<li><%# Eval(AddedByName") %></li><li>
Add comment</li></ul>
<div id='addComment<%# Eval("NoteID") %>' class="tierOne" style="display:none">
<asp:TextBox ID="commentreplytext" runat="server" rows="4"> </asp:TextBox>
<asp:HiddenField id="ParentIdReply" value='<%#Eval("NoteID")%>' runat="server" />
<asp:Button ID="Button2" runat="server" Text="Add" CommandArgument='<%#Eval("NoteID")%>' OnCommand="Add_Comment" />
</div>
</div>
</ItemTemplate>
</asp:Repeater>
.cs page:
repeater1.DataSource = FindNotes(ParentNote.ID);
repeater1.DataBind();

Transferring DataBound ID from aspx to codebehind

I have an Unsubscribe page(Unsubscribe.aspx) that generates three radio buttons and a text field by using a repeater.
The id's of the radio buttons come from databinding and I need to get those ID's to use in the code page but I can't seem to get it to recognize the existence of this binding.
Unsubscribe.aspx looks like this:
<asp:Repeater ID="rptReasons" runat="server">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<div>
<div class="col-lg-12">
<label class="radio-custom">
<input id='rbReason<%# DataBinder.Eval(Container, "DataItem.ID")%>' type="radio" name="rbReason" value='<%# DataBinder.Eval(Container, "DataItem.ID")%>'>
<i class="fa fa-circle-o"></i>
<label for='rbReason<%# DataBinder.Eval(Container, "DataItem.ID")%>'><%# DataBinder.Eval(Container, "DataItem.Explanation")%></label>
</label>
<%# (DataBinder.Eval(Container.DataItem, "ReasonType").ToString() == "OTH") ? "<input class='form-control m-t m-l-n-md' name='txtComment' type='text' maxlength='100' style='width:300px;' />" : "" %>
</div>
</div>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
And this is the behaviour I want to achieve:
if (DataItem.ID == checked )
{
disable the text area
}
try to add
runat="server"
<input runat="server" id='rbReason<%# DataBinder.Eval(Container, "DataItem.ID")%>' type="radio" name="rbReason" value='<%# DataBinder.Eval(Container, "DataItem.ID")%>'>
after that you need to find control on event
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item)
{
Label lbl = (Label)e.Item.FindControl("Label1");
LinkButton link = (LinkButton)e.Item.FindControl("LinkButton1");
RadioButton rdbtn = (RadioButton)e.Item.FindControl("control_id");
}
}

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?

Categories