I've been working on a small project for a chatbox using ASP.NET and WebForms and basically I'm stuck trying to change the class of a panel so I can determine if the message should be placed on the left or the right side of the box depending on who sent it.
This is how I'm currently using all of this:
<div class="lv-body" id="ms-scrollbar" style="overflow:scroll; overflow-x: hidden; height:520px;">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick" Interval="1000"></asp:Timer>
<asp:DataList ID="DataList3" runat="server">
<ItemTemplate>
<asp:Panel class="lv-item media" id="MessageBox" runat="server">
<div class="media-body">
<div class="ms-item">
<span class="glyphicon glyphicon-triangle-left" style="color:#000000;"></span>
<asp:Label ID="Message" runat="server" Text='<%# Bind("Message") %>'></asp:Label>
</div>
<small class="ms-date">
<span class="glyphicon glyphicon-time"></span>
<asp:Label Width="900px" ID="Date" runat="server" Text='<%# Bind("Date") %>'></asp:Label>
</small>
</div>
</asp:Panel>
</ItemTemplate>
</asp:DataList>
</ContentTemplate>
</asp:UpdatePanel>
</div>
This is how I'm populating the values through CodeBehind:
public void LoadChatbox()
{
DateTime date = DateTime.Now;
string date3 = date.ToString("dd-MM-yyyy");
MySQL.MySqlCommand Cmd = new MySQL.MySqlCommand(MySQL.MySqlCommandType.SELECT);
Cmd.Select("helpdesk").Where("Sender", Label1.Text).And("Receiver", Label2.Text).Or("Sender", Label2.Text).And("Receiver", Label1.Text).Order("UniqueID");
MySQL.MySqlReader R = new MySQL.MySqlReader(Cmd);
DataList3.DataSource = R._dataset;
DataList3.DataBind();
}
Everything is working fine but basically I need a way to determine if the MessageBox (Panel) is displayed on the left or right side. Adding "right" to its class would do it but I would need a way to do that.
EDIT: The Label1 is representative of my name/id and the Label2 represents the name/id of the other member of the chat so these values can be used to determine if I sent it or the other person did.
I would say, in pseudo code :
<% if (Sender==me){ %>
<div class="media-body" style="text-align: right;">
...
</div>
else
<div class="media-body" style="text-align: left;">
...
</div>
<% } %>
Besides you'd better use a parametrized query, this line of code is dangerous :
Cmd.Select("helpdesk").Where("Sender", Label1.Text).And("Receiver", Label2.Text).Or("Sender", Label2.Text).And("Receiver", Label1.Text).Order("UniqueID");
Related
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
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();
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?
I have textbox with an id #txtUserEntry where user can put the number of their family member living in their house and a button #btnAddOccupant to click after they put a number in textbox and #divOccupantProfile should show up depends on the number entered so it means 1 family member is equal to 1 #divOccupantProfile
aspx code
<tr>
<td style="text-align:left"><asp:Label ID="lbUserEntry" runat="server" Text="Number of House occupant"></asp:Label></td>
<td><asp:TextBox ID="txtUserEntry" class="basetxt" runat="server" Width="290"></asp:TextBox></td>
</tr>
<tr>
<td style="text-align:left"><asp:Button ID="btnAddOccupant" runat="server" Text="+" />
<asp:Label ID="lbres5" runat="server" Text="Add Occupant"></asp:Label></td>
</tr>
divOccupantProfile
<div id="divOccupantProfile">
<asp:Label ID="OPfamilyname" runat="server" Text="Family Name"></asp:Label>
<asp:TextBox ID="textOPfamilyname" runat="server"></asp:TextBox><br />
<asp:Label ID="OPfirstname" runat="server" Text="First Name"></asp:Label>
<asp:TextBox ID="textOPfirstname" runat="server"></asp:TextBox><br />
<asp:Label ID="OPmiddlename" runat="server" Text="Middle Name"></asp:Label>
<asp:TextBox ID="textOPmiddlename" runat="server"></asp:TextBox><br />
<asp:Label ID="OPmaritalstatus" runat="server" Text="Marital Status"></asp:Label>
<asp:DropDownList ID="ddlOPmaritalstatus" runat="server" >
<asp:ListItem></asp:ListItem>
<asp:ListItem>Married</asp:ListItem>
<asp:ListItem>Single</asp:ListItem>
<asp:ListItem>Divorced</asp:ListItem>
</asp:DropDownList><br />
<asp:Label ID="OPoccupation" runat="server" Text="Occupation"></asp:Label>
<asp:TextBox ID="textOPoccupation" runat="server"></asp:TextBox><br />
<asp:Label ID="OPrelationship" runat="server" Text="Relationship"></asp:Label>
<asp:DropDownList ID="ddlOPrelationship" runat="server" >
<asp:ListItem></asp:ListItem>
<asp:ListItem>Wife</asp:ListItem>
<asp:ListItem>Daughter</asp:ListItem>
<asp:ListItem>Son</asp:ListItem>
<asp:ListItem>Father</asp:ListItem>
<asp:ListItem>Mother</asp:ListItem>
<asp:ListItem>House helper</asp:ListItem>
<asp:ListItem>Driver</asp:ListItem>
</asp:DropDownList>
</div>
can someone show me an example how to do this one
something like
$('#btnAddOccupant').click(function(){
var occupants = $('#txtUserEntry').val();
//here some check on occupants.....
for(int i = 0;i<occupants;i++){
$(somewhere).append($('#divOccupantProfile').html());
}
})
Some suggestions:
because you are going to use multiple divOccupantProfile, it's better to use selectors based on the class instead of ID, otherwise in your page you'll have 1+ elements with the same ID.
The $(somewhere)
is the "container" where you want to put all the div related to each occupant profile
Also note that the .html() function will copy the html INSIDE the div, exluding the div itself. So if you want to have N elements formed in this way
<div class="occupantProfile">...</div>
<div class="occupantProfile">...</div>
you have to use
somewhere.append($('<div').append($('.occupantProfile')).html())
Here i have made a sample for what you should find helpful
HTML
<input type="text"http://jsfiddle.net/#save id="txtnum" />
<input type="button" value="click" id="btnSubmit" />
<div id="divOccupantProfile1">Data 1</div>
<div id="divOccupantProfile2">Data 2</div>
<div id="divOccupantProfile3">Data 3</div>
<div id="divOccupantProfile4">Data 4</div>
<div id="divOccupantProfile5">Data 5</div>
CSS
div[id^="divOccupantProfile"] {
display:none;
}
Jquery
$("#btnSubmit").click(function(){
var num = $("#txtnum").val();
$("#divOccupantProfile"+ num).css("display","block");
})
Demo Link
I have created FAQ page using Repeater Control, The questions and Answers are bound Run-time from Code Behind as Follows.
ASPX code
<asp:Repeater ID="RepDetails" runat="server">
<ItemTemplate>
<table id="tblRepeater">
<tr id="QARow" runat="server">
<td>
<div id="QuestionDiv" onclick="return show(this, 'AnswerDiv');">
Q:<asp:label id="lblQuestion" runat="server" Text='<%# Eval("Question")%>' CssClass="lblQueClass"></asp:label>
</div>
<div id="AnswerDiv" style="display:none;">
Ans:<asp:Label id="lblAnswerClass" runat="server" Text='<%# Eval("Answer")%>' CssClass="lblAnswerClass"></asp:Label>
</div>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
It Works great ! The thing is i have used following Script for opening and closing the Answer.
<script type="text/javascript">
function show(QuestionDiv, AnswerDiv) {
var arrDIVs = QuestionDiv.parentNode.getElementsByTagName("Div");
for (var i = 0; i < arrDIVs.length; i++) {
var oCurDiv = arrDIVs[i];
if (oCurDiv.id.indexOf(AnswerDiv) >= 0) {
var blnHidden = (oCurDiv.style.display == "none");
oCurDiv.style.display = (blnHidden) ? "block" : "none";
}
}
return false;
}
</script>
It works like, when clicked on One Question It shows the answer of that question.
My Question is: I want to update the script so as when we click on One particular question, It should display the Answer of that question, also it should hide the Answer of other Question.(like http://www.edubrainschool.com/faq.php).
The best way for that would be to bind click of that TR. You can do this by applying a css to the TR.
<asp:Repeater ID="RepDetails" runat="server">
<ItemTemplate>
<table id="tblRepeater">
<tr id="QARow" runat="server" class="TROpenCSS">
<td>
<div id="QuestionDiv" class="QuestionCSS" onclick="return show(this, 'AnswerDiv');">
Q:<asp:label id="lblQuestion" runat="server" Text='<%# Eval("Question")%>' CssClass="lblQueClass"></asp:label>
</div>
<div id="AnswerDiv" class="AnswerCss" style="display:none;">
Ans:<asp:Label id="lblAnswerClass" runat="server" Text='<%# Eval("Answer")%>' CssClass="lblAnswerClass"></asp:Label>
</div>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
And the bind the click event of those CSS
$('.TROpenCSS').bind('click',function(){
// Do your code to show the TD
});
Add other bind for all clicks / mouseover
Or you can use "ddaccordion.js" or refer to the following link