asp.net set Session variable and execute a javascript function - c#

net/C# application I have a Link button:
<asp:LinkButton runat="server" ID="LinkButton1"/>
When the user clicks this button I want to execute this javascript function:
document.getElementById('LinkButtonPrevious').click();
And change a Session variable:
Session["ID"] = 2;
The problem is that the session variable can only be changed in the code behind.
How can I execute both when the link button is clicked?
Thanks in advance

Changing a value server side requires either a full post of the page or an ajax call.
So you could add a HiddenField and set its value to 2 client side, and then in your server side button handler use that value to set the session variable.
Or you could do an ajax call to a web service.
As far a performing client and server side operations on the same click event, you can do the following. Add a server side Click handler as usual, then register a client side event with ClientScriptManager.RegisterOnSubmitStatement. Here's the example from MSDN:
<%# 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">
public void Page_Load(Object sender, EventArgs e)
{
// Define the name and type of the client script on the page.
String csname = "OnSubmitScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the OnSubmit statement is already registered.
if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
{
String cstext = "document.write('Text from OnSubmit statement');";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>ClientScriptManager Example</title>
</head>
<body>
<form id="Form1"
runat="server">
<input type="submit"
value="Submit" />
</form>
</body>
</html>

You May have to Use ClientCallBack ...
here is an example of it..
MSDN lINK FOR CLIENT CALLBACK
<script type="text/ecmascript">
function LookUpStock() {
var lb = document.getElementById("ListBox1"); // this two statements set your javascript
var product = lb.options[lb.selectedIndex].text;
CallServer(product, ""); //this method contains code where you set session variable
}
function ReceiveServerData(rValue) {
document.getElementById("ResultsSpan").innerHTML = rValue;
}
</script>

Related

dynamically load a user control in the aspx page

I have the following aspx page for eg: called choosemenu.aspx
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<div id="renderhere" runat="server">render user control here </div>
</form>
</body>
</html>
I have a list of ascx pages called
english.ascx
commerce.ascx
maths.ascx
I have to dynamically load the ascx files in my aspx page depending on the querystring in the aspx page.
I have the following contents in my aspx page in page_load event.
var control = (English)Page.LoadControl("/ascx/english.ascx");
How will I render the contents of the english.ascx page in the choosemenu.aspx that too in this tag
Also I have to pass some value in the ascx file. This is the static stuff.
<Menu:MNU ID="english" runat="server" HiLiter="<%#h %>"></Menu:MNU>
Loading a control from the server side
protected void Page_Load(object sender, EventArgs e)
{
Page.Controls.Add(Page.LoadControl("~/ascx/english.ascx")); //CHECK THE PATH
}
Loading a control from the server side and rendering it into a div
If you want to render it in a specific div you might write:
protected void Page_Load(object sender, EventArgs e)
{
UserControl uc = (UserControl)Page.LoadControl("~/ascx/english.ascx");
uc.MyParameter = 1;
uc.Id = 2;
uc.someMethodToInitialize();
div1.Controls.Add(uc);
}
and in your aspx page:
<div id="div1" runat="server">
</div>
Loading a control from the server side initializing the control with parameters
If your control has a constructor with parameters, you have to use:
public English_Control(int MyParameter, int Id)
{
//code here..
}
In you aspx.cs file you can initialize with:
UserControl uc = (UserControl)Page.LoadControl(typeof(English_Control), new object[] {1, 2});
div1.Controls.Add(uc);
In order for the control's postback values to be available, you must load and reload it no later than PreInit. Here is the code you need to do that.
protected override void OnPreInit(EventArgs e)
{
string controlToLoad = String.Empty;
//logic to determine which control to load
UserControl userControl = (UserControl)LoadControl(controlToLoad);
renderhere.Controls.Add(userControl);
base.OnPreInit(e);
}
As per MSDN:
Pre-Init event used to "Create or re-create dynamic controls."

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>

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;

Simple chat application signal r

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 :)

Call non-static method in server-side from client-side using JavsScript

How do I call a non-static method in server side(aspx.cs) from client side using javascript (aspx)....?
As far as I know I can call static method in server side from client side...
server side:
[WebMethod]
public static void method1()
{
}
client side:
<script language="JavaScript">
function keyUP()
{
PageMethods.method1();
}
</script>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
It works. Now how do I call non-static method from client side?
You can avoid the static constraint by using a simple .asmx page instead of the codebehind page.
1) Open New Website using the AJAX Enable ASP.NET template (it puts the necessary references in the web.config)
2) SIMPLESERVICE.ASMX - Add a new .asmx web service (I called mine SimpleService.asmx)
Notice the [System.Web.Script.Services.ScriptSerive] decoration and that the SimpleService class implements Webservice.
<%# WebService Language="C#" Class="SimpleService" %>
using System;
using System.Web.Services;
[System.Web.Script.Services.ScriptService]
public class SimpleService : WebService
{
[WebMethod]
public string GetMessage(string name)
{
return "Hello <strong>" + name + "</strong>, the time here is: " + DateTime.Now.ToShortTimeString();
}
}
3) DEFAULT.ASPX - To use it reference the service in you script manager and you are off and running. In my Javascript I call the class.method - SimpleService.GetMessage.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script language="javascript" type="text/javascript">
function callServer() {
SimpleService.GetMessage($get("Name").value, displayMessageCallback);
}
function displayMessageCallback(result) {
$get("message").innerHTML = result;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" >
<Services>
<asp:ServiceReference Path="~/SimpleService.asmx" />
</Services>
</asp:ScriptManager>
<div>
</div>
<h1>Hello World Example</h1>
<div>
Enter Name: <input id="Name" type="text" />
Call Server
<div id="message"></div>
</div>
</form>
</body>
</html>
I used the example I found from Scott Gu
Found Here.
No you cannot call non-static methods from client side per se. I've tried it once but it is ugly one (also I used jQuery ajax). Just call the page using ajax with method name appended to it as query string parameter and then on server side check the parameter and call the relevant method. But as I've told you it is pretty ugly :(
$.ajax({'/mypage.aspx?m=mymethod',......}); //this is not correct syntax
on server side:
protected void Page_Load(object sender, EventArgs e)
{
if(!Request.QueryString.HasKeys() ||
string.IsNullOrEmpty(Request.QueryString["m"]))
{
//return error or something relevant to your code
}
var m = Request.QueryString["m"];
switch(m)
{
case "a":
a();
break;
.....
.....
}
}
Actually, you don't get to call non-static methods in this way.
When you are calling a PageMethod, you're basically calling a special web service. This feature only works with static methods on the same page.
C#
public string LoadString() {
return "my string";
}
JS/jQuery
$('#txt').val(<%= LoadString() %>);
as an answer to Pramulia
i think you want to have a function with an argument from the client side which is implemented in the example -> CallServer(arg1, arg2)
<%# Page Language="C#" AutoEventWireup="true" %>
<%# Implements Interface="System.Web.UI.ICallbackEventHandler" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head runat="server">
<title>Client Callbacks</title>
<script runat="server">
public void RaiseCallbackEvent(String eventArgument)
{
// Processes a callback event on the server using the event
// argument from the client.
}
public string GetCallbackResult()
{
// Returns the results of a callback event to the client.
string dateString = DateTime.Now.ToLongDateString();
return dateString;
}
void Page_Load(object sender, EventArgs e)
{
ClientScriptManager cm = Page.ClientScript;
String cbReference = cm.GetCallbackEventReference(this, "arg",
"ReceiveServerData", "");
String callbackScript = "function CallServer(arg, context) {" +
cbReference + "; }";
cm.RegisterClientScriptBlock(this.GetType(),
"CallServer", callbackScript, true);
}
</script>
<script type="text/javascript">
function ReceiveServerData(arg, context) {
Message.innerText = "Date from server: " + arg;
}
</script>
</head>
<body>
<h2>Client Callbacks Without Postbacks</h2>
<form id="form1" runat="server">
<input type="button" value="Callback"
onclick="CallServer('1', alert('Callback sent to Server'))" />
<br />
<span id="Message"></span>
</form>
</body>
</html>
If you want to call it using the same function, you can use the following code:
[WebMethod]
public static void method1()
{
ClassOfNonStaticFunction obj = new ClassOfNonStaticFunction();
obj.yourFunctionName(ParametersIfAny);
}
I ended up using hidden fields in case anyone reads this. I can set the value in c# under a function and then read it in javascript.
Dave has written in detail about calling page methods from client side using jquery ajax. The general idea is like this (if you find any problem please refer to Dave's site).
C# Code:
[WebMethod]
public static string yourmethod(/*params*/)
{
return "Hello World!"
}
ASPX:
$.ajax({
type: 'POST',
data: /*Your Data*/,
dataType: 'JSON',
contentType: 'application/json',
url: '/yourpage.aspx/yourmethod',//Method to call
success: function(result, status) {
//handle return data
},
error: function(xhr, status, error) {
//handle error
}
});

Categories

Resources