I need to add variable into session state using ajax , when I tries this It didn't work. can any one please help me on this. when I click the Button It redirect to Travellerinfo.aspx page
Below is my test.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="hotelbeds.test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Tooltip - Custom animation demo</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script type="text/javascript">
function testbook(hotelcode) {
$.ajax({
type: "POST",
url: "test.aspx/addSession",
data: "{'hotelcode':'" + hotelcode + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
window.location.href = "Hotelresul.aspx";
},
error: function (err) {
window.location.href = "TravellerInfo.aspx";
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
CS test.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Services;
using System.Configuration;
using System.Drawing;
namespace hotelbeds
{
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs ea)
{
ImageButton testbtn = new ImageButton();
testbtn.OnClientClick = "testbook('15000')";
form1.Controls.Add(testbtn);
}
[WebMethod(EnableSession = true)]
public static void addSession(String hotelcode)
{
HttpContext.Current.Session.Add("hotelcode", hotelcode);
}
}
}
It must be
[WebMethod (EnableSession=true)]
public static void addSession(String hotelcode)
{
HttpContext.Current.Session.Add("hotelcode", hotelcode);
}
Please Note: The method must be public, static and EnableSession attribute must be true.
EDIT 1:
'return false' is added to prevent the Default function of a button. The default function of a button is to post form to server. Alternatively, event.preventDefault() can be used to prevent the default functionality.
<script type="text/javascript">
function testbook(hotelcode) {
$.ajax({
type: "POST",
url: "test.aspx/addSession",
data: "{'hotelcode':'" + hotelcode + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
window.location.href = "Hotelresul.aspx";
},
error: function (err) {
window.location.href = "TravellerInfo.aspx";
}
});
return false;
}
</script>
EDIT 2:
protected void Page_Load(object sender, EventArgs ea)
{
ImageButton testbtn = new ImageButton();
testbtn.OnClientClick = "return testbook('15000')";
form1.Controls.Add(testbtn);
}
Related
This question already has an answer here:
How to refer http handler file from jQuery ajax under different directory of asp.net web application
(1 answer)
Closed 5 years ago.
I created a http handler file in following directory of my application
I am referring this handler from common.js file using jQuery ajax and common.js file referred in aspx pages StoresSummary.aspx & EmoloyeeProfile.aspx
From EmoloyeeProfile.aspx I am able to call the handler and getting the output, but from StoresSummary.aspx jquery ajax call getting failed.
I know the cause of failure because the path of CommonHandler.ashx file does not map correctly due to location hierarchy of StoresSummary.aspx.
This is a sample code I am posting, the http handler file I need to call from jQuery ajax and aspx pages may exists in different directory of same web application.
How do I give path of CommonHandler.ashx in ajax jQuery call so any location hierarchy of my aspx page can call it.
This is my code
common.js
function GetMessage(key) {
var message = '';
$.ajax({
type: 'POST',
url: '../../Common/Handlers/CommonHandler.ashx', /*Working for EmoloyeeProfile.aspx but not for StoresSummary.aspx*/
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: { 'MessageKey': key },
success: onSucess,
error: OnFailed,
async: false
});
function onSucess(res) {
message = res;
}
function OnFailed(res) {
alert('failed');
}
return message;
}
CommonHandler.ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
namespace DemoWebApp.Common.Handlers
{
/// <summary>
/// Summary description for CommonHandler
/// </summary>
public class CommonHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(GetData(context.Request["MessageKey"]));
context.Response.ContentType = "text/html";
context.Response.Write(result);
}
private string GetData(string Id)
{
return DateTime.Now.ToString(); //just to demostrate
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
StoresSummary.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="../../../Common/Scripts/common.js"></script>
<script src="../../../Common/Scripts/jquery-1.9.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Get Message" OnClientClick="return CallMethod();" />
</div>
</form>
<script type="text/javascript">
function CallMethod() {
var msg = GetMessage('001');
alert(msg);
return false;
}
</script>
</body>
</html>
EmoloyeeProfile.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="../Common/Scripts/common.js"></script>
<script src="../Common/Scripts/jquery-1.9.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Get Message" OnClientClick="return CallMethod();" />
</div>
</form>
<script type="text/javascript">
function CallMethod() {
var msg = GetMessage('001');
alert(msg);
return false;
}
</script>
</body>
</html>
Provide absolute path to the handler. You are providing relative path now. See the ajax url section.
$.ajax({
type: 'POST',
url: '/Common/Handlers/CommonHandler.ashx', /*Working for EmoloyeeProfile.aspx but not for StoresSummary.aspx*/
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: { 'MessageKey': key },
success: onSucess,
error: OnFailed,
async: false
});
I'm using Visual Studio 2015 and the project is in .NET 4.5.2
I choose the default template so there are some things like the Master Site and Default.aspx that are in the solution but I have not touched them...
I added a page, Welcome.aspx and Can't seem to get the PageMethods to work properly.
Welcome.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Welcome.aspx.cs" Inherits="MyProject.Welcome" %>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.0.3/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.0.3/dist/leaflet.js"></script>
<link rel="stylesheet" href="CSS/WelcomeCSS.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css" />
</head>
<body>
<form id="WelcomeForm" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server"></asp:ScriptManager>
<div> ... some more html... non <asp:controls>...</div>
<script type="text/javascript">
//PageMethods.TestMarker(); // throws exception - PageMethods is undefined.
$.ajax({
type: "POST",
dataType: 'text',
contentType: "text",
url: "Welcome.aspx/TestMarker()",
data: "{val = adrian}", // parameters for method
success: function (dt) { alert("HI"+dt); }, //all Ok
error: function (dt) { alert(dt); } // some error
}); // doesn't seem to throw an error but C# never gets called
</script>
</form>
</body>
</html>
Welcome.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace HomeVenues
{
public partial class Welcome : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
protected static void TestMarker(string val)
{
return;
}
}
}
I have the following references:
- system.web.extensions
Q: What am I missing to call my server side code?
Try making changes to the below lines of code:
public static void TestMarker(string val) //Method should be public
url: "Welcome.aspx/TestMarker", //Dont need enclosing braces
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({val:"adrian"}),
Change your Protected WebMethod to Public as follows :
[WebMethod]
Public static void TestMarker(string val)
{
return;
}
Change your client side script ajax call as follows :
<script>
$.ajax({
type: "POST",
dataType: 'text',
contentType: "text",
url: "Welcome.aspx/TestMarker",
data: '{ val:"adrian" }', // parameters for method
success: function (data) { alert("HI" + data.d); }, //all Ok
error: function (data) { alert(data); } // some error
});
</script>
Explanation :- Do remember following points :
public
The type or member can be accessed by any other code in the same assembly or another assembly that references it.
protected
The type or member can only be accessed by code in the same class or struct, or in a derived class.
private
The type or member can only be accessed by code in the same class or struct.
I need to pass User Guid to the Ajax function,But when i tried i'm getting error
SyntaxError: identifier starts immediately after numeric literal
My Serverside Code
public Guid GetUserID()
{
Guid currentUserId = (Guid)Membership.GetUser().ProviderUserKey;
return currentUserId;
}
Part of Client Side Code
<script>
$(function () {
LoadUserUploadFiles();
});
id = "<%=GetUserID()%>";
function LoadUserUploadFiles(id) {
alert(id);
var url = '<%= ResolveUrl("/WebMethods.aspx/GetIndividuallyUploadedFiles") %>';
$.ajax({
url: url,
type: "POST",
data: JSON.stringify({ id: id }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (Result) {
var html = '<table class="table-hover">';
html += '<thead>';
html += '<th>Username</th>';
html += '<th>Upload Date</th>';
html += '<th>Download</th>';
html += '<th></th>';
html += '</thead>';
html += '<tbody>';
$.each(Result.d, function (key, value) {
html += '<tr>';
html += '<td>' + value.UserName + '</td>';
html += '<td>' + value.DateStr + '</td>';
html += '<td>' + 'Download' + '</td>';
html += '<td>' + '<input type="button" value="Delete" onclick="deleteUploadFile(this,' + value.Id + ')" >' + '</td>';
html += '</tr>';
});
html += '</tbody>';
html += '</table>';
$("#uploaddata").html(html);
},
error: function (e, x) {
alert(x.ResponseText);
}
});
}
In function signature you should have the parameter name. While calling the function you should pass the guid to the function. See the example below:
MARKUP:
<%# 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>
</head>
<body>
<form id="form1" runat="server">
<div>
<script>
// Notice "id" is the parameter name here
function LoadUserUploadFiles(id){
alert(id);
};
</script>
<input id="test" type="button" value="test" onclick='LoadUserUploadFiles("<%=GetUserID()%>")' />
</div>
</form>
</body>
</html>
CODE:
using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public Guid GetUserID()
{
Guid currentUserId = (Guid)Membership.GetUser().ProviderUserKey;
return currentUserId;
}
}
EDIT:
You can change you code like this:
<script>
$(function () {
LoadUserUploadFiles('<%=GetUserID()%>');
function LoadUserUploadFiles(id) {
alert(id);
var url = '<%= ResolveUrl("/WebMethods.aspx/GetIndividuallyUploadedFiles") %>';
$.ajax({
//Rest of the code goes here
Wrap quotes around the GetUserId call.
function LoadUserUploadFiles("<%=GetUserID()%>")
I found this answer by Googling. Always make a search engine your first stop before asking question.
I am using Jquery auto complete text box , in that i am entering a name starts with z or something which is not available in the database, at that time I need to display a custom message in auto complete mentioning that "No Datas Found"
I came up with a solution,please Correct me if the below mentioned solution is incorrect or any other alternate way to achieve it.
Thanks in advance.
AutoComplete TextBox.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="AutoCompleteTextBox.aspx.cs" Inherits="Ajax_Using_Jquery.AutoCompleteTextBox" %>
<!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>Ajax Auto Complete Using Jquery</title>
<script type="text/javascript" src="JQuery/jquery-1.9.0.mini.js"></script>
<script type="text/javascript" src="JQuery/jquery-ui.min.js" ></script>
<%--<link type="text/css" href="StyleSheet/jquery-ui.css" rel="Stylesheet" />--%>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<%--<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script> --%>
<script type="text/javascript">
$(document).ready(function () {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AutoCompleteFetchService.asmx/getUserNames",
data: "{'TextBoxVal':'" + document.getElementById('txtName1').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
if (data.d == "" || data.d == null || typeof (data.d) == 'undefined') {
response(["no search found"]);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error " + XMLHttpRequest);
alert("error " + textStatus);
alert("error " + errorThrown);
}
});
}
});
});
</script>
<%-- <link href="StyleSheet/jquery-ui.css" type="text/css" rel="Stylesheet" />--%>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
<div>
User Name :
<input type="text" id="txtName1" class="autosuggest" />
</div>
</td>
</tr>
</table>
</form>
</body>
</html>
AutoCompleteFetchService.asmx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
namespace Ajax_Using_Jquery
{
/// <summary>
/// Summary description for AutoCompleteFetchService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService()]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class AutoCompleteFetchService : System.Web.Services.WebService
{
[WebMethod]
public List<string> getUserNames(string TextBoxVal)
{
string strCon;
List<string> objList = new List<string>();
strCon = ConfigurationManager.ConnectionStrings["EmpNameFetch"].ConnectionString;
SqlConnection con = new SqlConnection(strCon);
SqlCommand cmd = new SqlCommand(#"select EmpName from newTb2 where EmpName like '%" + TextBoxVal + "%'", con);
con.Open();
SqlDataReader objReader = cmd.ExecuteReader();
while (objReader.Read())
{
objList.Add(objReader["EmpName"].ToString());
}
con.Close();
return objList;
}
}
}
The following prints "0 results" if no results are found and, if results are found, prints a helpful message to the user that says "Click or Arrow Up/Down"
messages: {noResults: '0 Results',results: function() {return 'Click or Arrow U/D'; } }
i have the following jquery postback method on the client
<%# Page Language="C#" AutoEventWireup="true" CodeFile="CallServerWithParameters.aspx.cs" Inherits="CallServerWithParameters" %>
<!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="jquery-1.2.6.js" type="text/javascript"></script>
<script language="javascript">
$(document).ready(function() {
$("#txtNoOfMales").change(function() {
var ticketRequired = this.value;
var options = {
type: "POST",
url: "CallServerWithParameters.aspx/GetAvailableTicketsForMales",
data: "{no:" + ticketRequired + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
if (response.d != "") {
alert(response.d);
$("#txtNoOfMales").focus();
}
}
};
//Call the PageMethods
$.ajax(options);
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
No of Male Tickets:<asp:TextBox ID="txtNoOfMales" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
and the following web method on the server side
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
public partial class CallServerWithParameters : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetAvailableTicketsForMales(int no)
{
string result = "";
int NoOfTicketsAvailable = 5;
if (no > NoOfTicketsAvailable)
{
result = "Only " + NoOfTicketsAvailable.ToString() + " Male ticket(s) avaialable. Please eneter a lower number!";
}
return result;
}
}
problem is everything works fine on .net 3.5 but if i use the same code on .net 2.0 the
webmethod event does not get call at all, anybody have any idea what i did wrong?
thanks
updated with full source code
It works for my declaring the web method with the following attributes:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
Also I use PageMethods.GetAvailableTicketsForMales to call the function from js.
I hope this will help you.