Simple chat application signal r - c#

I am trying to modify a simply chat application for learning purposes. The only change i made was to change a button to a serverside control. The problem i have is that the first time i broadcast a message, it works, and the Clients.addNotification(msg) is called. Yet the second time, although the javascript works, at its final step, the javascript undos all the changes and the Clients.addNotification(..) is never called :/ It only works for the first time! I have to rebuild my project to see it working again (a page refresh won't work)
public class Chat : Hub
{
public void Send(string message)
{
// Call the addMessage method on all clients
Clients.addNotification(message);
}
}
My aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Client1.aspx.cs" Inherits="WebApplication1.WorkingWithHubs.Client1" %>
<!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">
<title></title>
<script src="../Scripts/jquery-1.6.4.js" type="text/javascript"></script>
<script src="../Scripts/jquery.signalR.min.js" type="text/javascript"></script>
<script src="/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var chat = $.connection.chat;
// Declare a function on the chat hub so the server can invoke it
chat.addNotification = function (message) {
$('#messages').append('<li>' + message + '</li>');
var labelValue = $('#total').val();
$('#total').val(parseInt(labelValue, 10) + 1);
};
$("#btn").click(function () {
// Call the chat method on the server
chat.send($('#msg').val());
});
// Start the connection
$.connection.hub.start();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="scriptManager" runat="server" />
<div>
<asp:UpdatePanel ID="updatePanel" runat="server">
<ContentTemplate>
<input type="text" id="msg" runat="server" />
<asp:Button ID="btn" runat="server" Text="BroadCast" OnClick="btn_click" ClientIDMode="static" />
<input type="text" id="total" value="0" />
<ul id="messages">
</ul>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
My code behind:
public partial class Client1 : System.Web.UI.Page
{
public List<String> list = new List<String>();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_click(object sender, EventArgs e)
{
list.Add(msg.Value);
}
}
Once this example work I will shift the code to another application I am working on so that notifications can be immediately pushed to all clients.
I am a very beginner and I would appreciate all your help! Thanks a lot guys!
EDIT:
when checking out the network tab (on my chrome), for the first click I get a 'send' (signalR) and Client1.aspx and all works fine, for the second click onwards, I only get Client1.aspx, and no send whatsoever :/

for a quick and dirty solution, just place the update panel ONLY around the button, and remove
$("#btn").click(function () {
// Call the chat method on the server
chat.send($('#msg').val());
});
and instead, insert the following in the beginning
$('#form1').delegate('#btn', 'click', function () {
chat.send($('#msg').val());
});
Thanks to my friends shifty and red_square :)

Related

I want to hide label whenever something is typed in text box in aspx page

I want to hide label, whenever something is typed in text box in aspx page.
I am trying something like this :
protected void txt_LastName_KeyPress(object sender, EventArgs e)
{
Label_msg.Visible = false;
}
protected void txt_LastName_KeyDown(object sender, EventArgs e)
{
Label_msg.Visible = false;
}
But it is not happening. Do I need to write something like this in focus event?
You need javascript
Here is an implementation using jQuery
<script>
$('#txt_LastName').focus(function() {
$('#Label_msg').hide();
});
$('#txt_LastName').blur(function() {
$('#Label_msg').show();
});
</script>
A plain vanilla javascript solution would be
<script>
document.getElementById("txt_LastName").onfocus = function() {
document.getElementById("Label_msg").style.display = 'none';
};
document.getElementById("txt_LastName").onblur = function() {
document.getElementById("Label_msg").style.display = 'inherit';
};
</script>
This one may be helpful for you. Do as following...
Firstly, Set Textbox's AutoPostBack Property to true
AutoPostBack="True"
Then, Use OnTextChanged Event
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Label1.Visible = false;
}
you can do some thing simple as below:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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">
<title></title>
<script language="javascript" type="text/javascript">
function hideOnKeyPress() {
document.getElementById('lblHidden').style.display = 'none';
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtMaintCost" onkeypress="hideOnKeyPress(); return true;" runat="server"></asp:TextBox>
<asp:Label ID="lblHidden" runat="server" Text="I'll hide when you type something in the text box" />
</div>
</form>
</body>
</html>
You can't change the visibility of a layer event based server side. You have to put this into a javascript procedure.
You have to possibilities: The easy way is, to use jQuery (you need to include jQuery!):
<script type="text/javascript">
$(function() {
$('#txt_LastName').focus(function() {
$('#Label_msg').hide();
});
$('#txt_LastName').blur(function() {
$('#Label_msg').show();
});
}
</script>
Second method: do it the hard way
If you don't want to use jQuery for some reason, you have to work directly with the DOM.
You can read about it there: W3Schools DOM Methods
You may want to look into a JavaScript MVVM library, such as KnockoutJS, like this:
<p>Your value: <input data-bind="value: someValue, valueUpdate: 'afterkeydown'" /></p>
<p>You have typed: <span data-bind="text: someValue"></span></p>
// Here's my data model
var viewModel = {
someValue: ko.observable("edit me")
};
ko.applyBindings(viewModel); // This makes Knockout get to work
Here is a jsFiddle to illustrate how easy it is to achieve your desired key down functionality with JavaScript via KnockoutJS.
a simple javascript solution would be
HTML
<span id="one">text</span>
<input type="text" onkeypress="hide()" />
Javascript
var isHidden = false;
function hide(){
if(!isHidden){
isHidden = true;
document.getElementById("one").setAttribute("style","display:none");
}
}
jsbin demo
Because there is no KeyPress Event in ASP.Net forms unlike Winforms you must use JQuery short hand code (for JavaScript) to handle hiding your label when user is typing in the textbox like this example:
<script>
$(document).ready(function () {
$("#txtUserName").keypress(function () {
$("#lblUser").hide();
});
});
</script>

Access the Label value on Page load in c# when value set through jQuery

I am posting this question again, maybe this time more accurate description.
The problem is , I am using jQuery to set the Label's text value and it works fine on browser, but when I want to save it to string, it does not save it. Here is the
front End Html Code.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(window).load(function () {
var myNewName = "Ronaldo";
$('#<%= Label1.ClientID %>').text(myNewName);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
</body>
</html>
And here is the Back End C# Code On Page Load
using System;
using System.Web.UI;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string mynameCheck = Label1.Text;
if (mynameCheck=="Ronaldo")
{
Response.Write("Yes Name is Fine");
}
else
{
Response.Write("Name's not Fine");
}
}
}
The result displayed is
Name's not Fine
Ronaldo
Seems like the string is still Null. Is there any problem of rendering??
label is not input type so you can not get changed values through jquery on server side. You can use hidden field for this purpose.
Your server side code (c#) can not access the form data until your client side code (HTML/Javascript) posts it.
Why do you want to the name already at the PageLoad event?
You could add a asp:Button with an attached onClick event handler to read the value of your asp:Label.
Labels do not maintain viewstate. The server will not post that information back to the server. You can try explicitly enabling the ViewState on your Label, but if that doesn't work, you will have to store that value in a hidden field.
First Call Page Load event and after that call JQuery Window.Load event.
So if you want to set any content in Label then you can do using onClientClick of button.
For ex.
<asp:Button ID="btn" runat="server" Text="Click me" OnClientClick="SetClientValues();" />
<script type="text/javascript">
function SetClientValues() {
var myNewName = "Ronaldo";
$('#<%= Label1.ClientID %>').text(myNewName);
}
</script>
At server side button event you can get Label values that sets at client side.
protected void btn_Click(object sender, EventArgs e)
{
string mynameCheck = Label1.Text;
if (mynameCheck=="Ronaldo")
{
Response.Write("Yes Name is Fine");
}
else
{
Response.Write("Name's not Fine");
}
}
It will print Yes Name is Fine
This should do it:
<script type="text/javascript">
$(window).load(function () {
if($('#<%= Txt1.ClientID %>').val() != "Ronaldo"){
var myNewName = "Ronaldo";
$('#<%= Txt1.ClientID %>').val(myNewName);
$('#<%= Label1.ClientID %>').text(myNewName);
$('#<%= Btn1.ClientID %>').click();
}
});
</script>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="Txt1" runat="server" style="display:none"></asp:Label>
<asp:Button ID="Btn1" runat="server" style="display:none" Click="Btn1_Click"></asp:Label>
</form>
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
Label1.Text=Txt1.Text;
string mynameCheck = Label1.Text;
if (mynameCheck=="Ronaldo")
{
Response.Write("Yes Name is Fine");
}
else
{
Response.Write("Name's not Fine");
}
}
}
protected void Btn1_Click(object sender, EventArgs e)
{ }
Hope it helps :)

get html DIV content from asp.net c# codebehind event

I want to get HTML DIV content via asp.net C# code behind event.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Report.aspx.cs" Inherits="WebApplication1.Report.Report" %>
<!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">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#_Hidden_CrystalReportContent').hide();
$('#_Hidden_CrystalReportContent').html("<b>I want to get Current value. 1<sup>st</sup></b>");
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="_Hidden_CrystalReportContent">I want to get Current value.</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</form>
</body>
</html>
My code behind file as below.
public partial class Report : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{}
protected void Button1_Click(object sender, EventArgs e)
{
string s = Request["_Hidden_CrystalReportContent"].ToString();
}
}
But I still cannot get div content value.
Please let me get your suggestion.
Make the div runat="server" to access on server.
Html
<div id="_Hidden_CrystalReportContent" runat="server">
Code behind
string htmlOfDiv = _Hidden_CrystalReportContent.innerHTML;
Javascript
$(document).ready(function () {
$('#<% _Hidden_CrystalReportContent.ClientID %>').hide();
$('#<%= _Hidden_CrystalReportContent.ClientID %>').html("<b>I want to get Current value. 1<sup>st</sup></b>");
});
Making a div server accessible by puttin runat="server" attribute cause the changed client id if CLientIDMode is not static. You will need to use ClientID attribute to get client id of div in javascript.
Edit: based on comments. You are trying to get the updated html, if so you then you wont get it as on post back only html form elements are posted. Put the changes in some hidden field and assess it on server.
In html
<input type="hidden" id="hdnDivContents" runat="server">
In javascript
$('#<% hdnDivContents.ClientID %>').val("<b>I want to get Current value. 1<sup>st</sup></b>");
In code behind
_Hidden_CrystalReportContent.innerHTML = hdnDivContents.Value;

Call jQuery function from server (In Updatepanel)

I want to call jQuery function from server.
The server side button that calls function is inside an UpdatePanel.
this is server side function :
//Button Click handler (It is inside Updatepanel)
string ScriptName = null;
ScriptName = "function pageLoad(sender, args) { if (args.get_isPartialLoad()) {DisplayMessage(); }}";
ScriptManager.RegisterStartupScript(this, GetType(), "DisplayMessage", ScriptName, true);
and this is client side function :
<script type="text/javascript">
function DisplayMessage() {
//Alert("Called");
}
</script>
It doesn't work.
What's wrong ? (Is my question and problem clear?)
That's weird, as the following works perfectly fine for me:
<%# Page Language="C#" %>
<script type="text/c#" runat="server">
protected void BtnTrigger_Click(object sender, EventArgs e)
{
string script = "function pageLoad(sender, args) { if (args.get_isPartialLoad()) {DisplayMessage(); }}";
ScriptManager.RegisterStartupScript(
this,
GetType(),
"DisplayMEssage",
script,
true
);
}
</script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
function DisplayMessage() {
alert('called');
}
</script>
</head>
<body>
<form id="Form1" runat="server">
<asp:ScriptManager ID="scm" runat="server" />
<asp:LinkButton
ID="BtnTrigger"
runat="server"
Text="Trigger"
OnClick="BtnTrigger_Click"
/>
<asp:UpdatePanel ID="up" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger
ControlID="BtnTrigger"
EventName="Click"
/>
</Triggers>
</asp:UpdatePanel>
</form>
</body>
</html>
Also do you really need all the complex script, why not simply use string script = "DisplayMessage();";?
create a display:none div in the page. Put it in update panel. This will not disturb your design. to execute every sclient side script in page
<div id="scriptContainer" runat="server" style="display:none;"></div>
then paste your js in it on an event.
scriptContainer.innerHTML = "<script type=text/javascript>DisplayMessage();</script>";
hope it helps.

Why is the label not changing color using RegisterClientScriptBlock?

I have an aspx page defined as follows:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" language='javascript'>
function changecolor() {
var lbl = document.getElementById('lblDisplayDate');
lbl.style.color = 'red';
};
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblDisplayDate" runat="server"
Text="Label"></asp:Label><br />
<asp:Button ID="btnPostBack2" runat="server"
Text="Register Client Block Script"
onclick="btnPostBack2_Click" />
</div>
</form>
Here is the btnPostBack2 Click event:
protected void btnPostBack2_Click(object sender, EventArgs e)
{
if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(),
"JSScriptBlock",
"changecolor();",
true);
}
}
Even though, I put the script in a function to change the color, it is still not doing it and why do I need to add the script tags to true if the function is already enclosed in script tags?
lblDisplayDate is in the Page Load where it is set to the current time on every page reload.
Change this line:
var lbl = document.getElementById('lblDisplayDate');
to:
var lbl = document.getElementById('<%= lblDisplayDate.ClientID %>');
Also, this probably isn't doing what you want it to do anyway. Try adding:
OnClientClick="changecolor()"
to your <asp:Button /> tag.
Edit At this point I am pretty confused as to what exactly you are trying to accomplish...
If you just want to change the color of the label without posting back, change your <asp:Button /> to a normal <input type="button" /> with an onclick handler and call your script, like this:
<input type="button" ... onclick="changeColor();" />
If you want to change the color of the label while posting back, then just change the label's background in the code-behind like this:
protected void btnPostBack2_Click(object sender, EventArgs e)
{
/* ... other stuff goes here ... */
lblDisplayDate.BackColor = Color.Red;
/* ... other stuff goes here ... */
}
like what Sean already stated: it is best to use OnClientClick in this case. OnClientClick would prevent a postback occuring - it is done dynamically using javascript. All u need to do is preference it to the javascript function.
I do not understand y u want to do a "RegisterStartupScript and RegisterClientScriptBlock" on colour change. These should be used when u want to add javascript from the code behind, but seeing that u have it written out already in the aspx page, its use is pointless.
Check this out. I have modified your code and its working fine now without postback.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" language='javascript'>
function changecolor() {
var lbl = document.getElementById('lblDisplayDate');
lbl.style.color = 'red';
};
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblDisplayDate" runat="server"
Text="Label"></asp:Label><br />
<asp:Button ID="btnPostBack2" runat="server"
Text="Register Client Block Script"
OnClientClick="changecolor(); return false" />
</div>
</form>
</body>
</html>
hope this helps

Categories

Resources