I have a usercontrol and in that I have a javascript function which makes a call to webmethod.
<%# Control Language="C#" AutoEventWireup="true" CodeFile="LeftMenu.ascx.cs"
Inherits="UserControls_LeftMenu" %>
<script type="text/javascript">
function GetRealTimeCount() {
PageMethods.CountOfMenus('', '', GetCountOfMenus_Success, GetCountOfMenus_Fail);
}
My webmethod code is
[System.Web.Services.WebMethod]
public static string CountOfMenus(string StartDate, string EndDate)
{
//Code here
}
But when I run the code, it gives me javascript error, CountOfMenus is undefined. I know the error is because it cant find the method in the current page but I want it to access method in the usercontrol.cs. I cant write the webmethod in every page as I have lots of pages where the usercontrol is used. Is there any way through which I can call the method of usercontrol.cs in javascript?
I solved this by below method
Javascript :
function GetRealTimeCount(StartDate, EndDate) {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "Default.aspx?Method=CountOfMenus&SD=" + StartDate + "&ED=" + EndDate;
xmlhttp.open("Get", url, false);
xmlhttp.send(null);
document.getElementById("Count").innerHTML = xmlhttp.responseText;
}
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Method"] == "CountOfMenus")
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
GetCount(Request.QueryString["SD"], Request.QueryString["ED"]);
}
}
private void GetCount(string StartDate, string EndDate)
{
Response.Clear();
// Code to get count
Response.Write(Count.ToString());
Response.End();
}
The below link from where I got these solutions has many other options to call C# methods from javascript
http://www.morgantechspace.com/2014/01/Call-Server-Side-function-from-JavaScript-in-ASP-NET.html
when your JS code calls a PageMethod using "PageMethods." , the call does not reach the page method if it was defined in the control. The page methods in the page are only callable.
I suggest another approach, using Http Handler which is also efficient.
Try follow this post:
Call HttpHandler from javascript
Also, the following post might be useful:
http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/
Do you have ScriptManager in your UserControl Page?
if not you have to add it and set EnablePageMethods="true"
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
Related
I have a img button. When it is clicked, I set the session value using jquery. however I cannot get the session on vb code behind. My process is like that after the user click the image, I set the session. When the user open popup page and return the page. I need to check the session to do something. However in the vb code, the session is nothing. Would some one tell me how to do it.
The below code call the function:
<asp:Image ID="img" runat="server" onclick="SetSession(hdID);" ImageUrl="pic_bottle.gif" />
The jquery script:
function SetSession(hdID) {
var hd = $('#' + hdID);
var hdValue = hd.val();
if (hdValue == "s") {
$.session.set('UpdateProdOrder', -1);
}
else {
var hdProdID = $('#hdProdID').val();
$.session.set("UpdateProdOrder", hdProdID);
}
alert($.session.get("UpdateProdOrder"));
}
The vb code behind never get the session
If Not Session("UpdateProdOrder") Is Nothing Then
'do something
updateOrder()
end if
The localStorage and sessionStorage properties allow saving key/value pairs in a web browser.
The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed).
These values are maintained on the client side, but you are trying to retrieve it on the server side. session variables are server side
Solution:
Method 1:
You'd have to have a little ajax call to talk to the server to set it.
please check it out
Method 2 :
Assigning the ASP.NET Session Variable using Javascript.
<script type="text/javascript">
function SetSession(hdID)
{
var hd = $('#' + hdID);
var hdValue = hd.val();
if (hdValue == "s") {
'<%Session["UpdateProdOrder"] = "' + -1+ '"; %>';
}
else {
var hdProdID = $('#hdProdID').val();
'<%Session["UpdateProdOrder"] = "' + hdProdID+ '"; %>';
}
alert('<%=Session["UpdateProdOrder"] %>');
}
</script>
Accessing ASP.NET Session variable using Javascript:
<script type="text/javascript">
function GetSession()
{
var updateProdOrder= '<%= Session["UpdateProdOrder"] %>';
alert(updateProdOrder);
}
</script>
You cannot change a server side Session object with javascript directly. You need to send it to the server somehow. This can be done by changing the image to an ImageButton and do a PostBack to modify the Session object. But since you seem to have some data in hdID. You cannot send that to the server with a ImageButton alone, you'll need a HiddenField
<asp:ImageButton ID="ImageButton1" runat="server" OnClientClick="SetSession(hdID);"
ImageUrl="pic_bottle.gif" OnClick="ImageButton1_Click" />
<asp:HiddenField ID="HiddenField1" runat="server" />
<script type="text/javascript">
var hdID = 'test';
function SetSession(hdID) {
$('#<%= HiddenField1.ClientID %>').val(hdID);
}
</script>
And then in code behind
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Session["UpdateProdOrder"] = HiddenField1.Value;
Label1.Text = string.Format("Session value is now '{0}'", Session["UpdateProdOrder"]);
}
You could do this also without the javascript SetSession, but that depends on where and when hdID is used on other parts of the page.
I'm developing a asp.net web application and I have this script in source code:
<script language="javascript" type="text/javascript">
function showWindow(URL, controlID, targetControlID,id)
{
noweOkno = window.open( URL + '?controlID='+controlID+'&targetControlID=' +
targetControlID+'&id='+ id, '_blank',
'menubar=no, toolbar=no, location=no, scrollbars=no, resizable=no, ' +
'status=no, width=760, height=600, left=30, top=30')
noweOkno.focus();
}
</script>
I can call it with this code:
Button4.Attributes["onClick"] = string.Format("showWindow( 'Child.aspx','{0}', '{1}','{2}');", tbVer.ClientID, Hidden1.ClientID, id_act);
my question is, how to call the javascript in some C# method like:
protected void someMethod()
{
-I want to call showWindow('Child.aspx','{0}', '{1}','{2}');", tbVer.ClientID, Hidden1.ClientID, id_act);
}
thanks
You can register script block to run on page like :
ClientScript.RegisterStartupScript(GetType(),"hwa","function_name;",true);
you can use clientscriptmanager
ClientScriptManager.RegisterStartupScript(this.GetType(), "AKey", "MyFunction();", true);
http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx
Here i am calling a javascript function on a button click and i need to call the server side method inside the javascript function after finishing its execution.
Javascript Function
function exportCharts(exportFormat) {
initiateExport = true;
for (var chartRef in FusionCharts.items) {
if (FusionCharts.items[chartRef].exportChart) {
document.getElementById("linkToExportedFile").innerHTML = "Exporting...";
FusionCharts.items[chartRef].exportChart({ "exportFormat": exportFormat });
}
else {
document.getElementById("linkToExportedFile").innerHTML = "Please wait till the chart completes rendering...";
}
}
}
Server side Method
protected void imgBTNExportPPT_Click(object sender, ImageClickEventArgs e)
{
try
{
PredictExportToPPT objOExporttoPPT = new PredictExportToPPT();
PredictionModel();
string reportNames = ObjCommon.GetBIReportNames("Prediction", "Report");
reportNames += ObjCommon.GetBIReportNames("Prediction", "Table");
objOExporttoPPT.ExportToPPTPredict(ObjPredictInputParameter, reportNames, ObjSharedEntities.PredictTableData);
string itemname = "PPTOutput.pptx";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "pptx";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + itemname + "");
HttpContext.Current.Response.BinaryWrite(System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(DataTemplate.PPTOutputTemplateFilePath)));
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
catch (Exception exceptionMessage)
{
throw (exceptionMessage);
}
finally
{
GC.Collect();
}
}
and i have tried like this
$(document).ready(function () {
$("#imgBTNExportPPT").click(function (e) {
e.imgBTNExportPPT_Click();
$.ajax({
type: "POST",
url: "PEventPerformance.aspx/updateContent",
data: "{}",
success: function (result) {
}
});
});
});
Any suggestion??
Your imgBTNExportPPT_Click looks like an click event of a button. You may try the following to raise the event from JavaScript
Place this javascript in aspx page
<script type="text/javascript">
function myfunc() {
<%= Page.ClientScript.GetPostBackEventReference(imgBTNExportPPT, String.Empty) %>;
}
</script>
Call this function against OnClientClick
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="myfunc();" />
This will fire the server side event:
protected void imgBTNExportPPT_Click(object sender, ImageClickEventArgs e)
{
}
You can use Ajaxpro for this purpose, If u want to generate a server side call without any event like button click.
In Your code behind file. Under the Page_Load section add
AjaxPro.Utility.RegisterTypeForAjax(typeof(YourCodebehindfilename));
In client side
call the server side method like
var content = YourCodeBehind.Yourmethod(optional parameters).value;
In content you can get your response as an object and can do further changes
I guess the best way to execute server side method is to use Web Services.
You have to write a Web Service that that contains your server side method.Then you can call it using AJAX.
I have the following block of code in my header:
<script type="text/javascript">
$(document).ready(function () {
$('#target').readmytweet({
'color': 'black',
'search': 'from:' + <%= GetUserName() %>,
'user': <%= GetUserName() %>,
'width': 600,
'tweets': 10,
'speed': 25
});
})
</script>
protected string GetUsername()
{
return "somestring..";
}
However, I am getting an error message:
The Controls collection cannot be modified because the control
contains code blocks (i.e. <% ... %>).
Does anyone know how I can pass a C# variable from my code behind into this jQuery function without getting that error?
Thanks in advance
For a dynamic string:
That seems like it would work, try wrapping the code blocks with quotes, as such:
'<%= GetUserName() %>'
also you may have to use a this statement to access that method:
'<%= this.GetUserName() %>'
For a static string:
Declare your string as a public string in your aspx page:
public string UserName = "somestring..";
and access it via:
var userName = <%=this.UserName%>;
This is a well-known problem when trying to add controls to a page that contains code blocks.
A simple workaround is to use data binding expressions instead, i.e., to use <%# ... %> instead of <%= ... %>. Note that you will have to call this.DataBind(); in your Page_Load event for this to work.
(BTW, remember that the code you insert in JavaScript will need to be properly quoted.)
Accessing a server-side c# variable/property within an .aspx page.
<script type="text/javascript">
<% string username = Class.PropertName; %>
var jsUsername = '<%: username %>';
</script>
I am using ASP.NET 3.5.
In my code behind i have this code that i want to execute from my JavaScript.
Private Sub CreateName()
Dim Name as String
Name = txtName.text
End Sub
And this is my JavaScript Function
<script type="text/javascript">
function doSomething() {
document.elqFormName.action = 'http://now.eloqua.com/e/f2.aspx'
document.elqFormName.submit();
}
</script>
So what must I place inside my JavaScript function to execute my function in my code behind?
Thanks in advance!!
I'm not sure how VB works, but it's similar to C#. I've previously done this by making a WebMethod and using ajax.
Although you could do this using WebMethods as Jimmeh stated, another option would be to use a HTML generic handler. In this approach, your CreateName method wouldn't be in a ASPX page but in a ASHX page.
Check:
http://www.aspcode.net/Creating-an-ASHX-handler-in-ASPNET.aspx
Inside your doSomething method in the javascript part you'd need to call the ASHX using Ajax.
Check:
http://docs.jquery.com/Ajax
I had this same issue, and I found the easiest way to handle it was with an AJAX call. In your ASPX page (javascript):
//======================================
/* This function creates a new instance of an XMLHttpRequest object,
based on the users browser, and returns it */
//======================================
var xmlhttp
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
//======================================
/* This function issues a request and specifies which function should handle the ajax response */
//======================================
function doSomething()
{
xmlhttp = GetXmlHttpObject();
xmlhttp.onreadystatechange=stateChanged;
var url = "CreateName.aspx"
xmlhttp.open("GET", url, false);
xmlhttp.send(null);
}
//======================================
/* This function handles the ajax response text, places it in a label */
//======================================
function stateChanged()
{
if (xmlhttp.readyState==4)
{
var returned = xmlhttp.responseText;
document.getElementById("lbl_returnStatus").innerHTML = returned;
}
}
And then in the file CreateName.aspx:
<%
'Here is where you can do anything on the server side
Dim Name as String
Name = txtName.text
'This is what will be passed back and handled by the stateChanged function
Response.Write("Success!")
%>
You can also pass parameters through an AJAX call if you need to. Since the type of request we are making is a GET, you can just add the parameters to the URL in Javascript and access them server side with the Request.Querystring("paramName") function.
I wrote a more detailed post on starting AJAX on my blog, here, if you'd like to read that as well. Cheers!