Implementing Session Variables in C# with AJAX

Can someone please assist me? I am trying to add a variable into the session state using AJAX, but it doesn't seem to be working. When I click the button, it redirects to Travellerinfo.aspx page.

Here 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>

C# 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);
}
}
}

Answer №1

It is required to

[WebMethod (EnableSession=true)]
        public static void createSession(String hotelId)
        {
            HttpContext.Current.Session.Add("hotelId", hotelId);
        }

Please keep in mind: The method should be declared as public, static, and the EnableSession attribute must be set to true.

EDIT 1:

The addition of 'return false' prevents the default action of a button. By default, a button would submit the form data to the server. You can also use event.preventDefault() as an alternative way to stop this default behavior.

<script type="text/javascript">
    function bookHotel(hotelId) {

        $.ajax({
            type: "POST",
            url: "test.aspx/createSession",
            data: "{'hotelId':'" + hotelId + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                window.location.href = "HotelResults.aspx";
            },
            error: function (err) {
                window.location.href = "TravelerInfo.aspx";
            }
        });

        return false;

    }

</script>

EDIT 2:

 protected void Page_Load(object sender, EventArgs e)
        {
            ImageButton testButton = new ImageButton();
            testButton.OnClientClick = "return bookHotel('15000')";
            form1.Controls.Add(testButton);
        }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Filtering a Two-Dimensional Array Using JavaScript

I am working with a basic 2D array that contains x, y coordinates as shown below: var c = [ [1,10], [2,11], [3,12], [4,13], [5,15] ]; I want to know how I can extract pairs from the array that meet specific conditi ...

How to insert an element INTO a JSON array using JavaScript

I'm having an issue with the way a line is displayed on my screen: Would you like to pay €xx to POS_ID Latte X 1....€2.50-Salad X 1....€4.00-Wrap X 1....€4.50-Coffee X 2....€3.00- My desired format is as follows: Would you like to pay ...

What is the best way to transfer values from an iterated object in HTML to a component in Angular 2/4?

My Angular2/4 app allows for file uploads to S3. The setup is such that when a user uploads a file, it will be stored in an S3 bucket. Once uploaded, the user will be shown the list of files they have uploaded. In case they upload the wrong file by mistake ...

Assign a value to the <li> element and modify the prop when the user clicks using vue.js

I've been attempting to update props from child to parent using the $event in an @click event. I sent the data and $event from the parent to the child as shown below. in the parent component: <v-filter :sortTypePrice="sortTypePrice" :sort ...

Press the "Reveal More" button to expand the content to its full size

I am currently working on coding a "read more" section using a button. I have looked at some existing solutions, but none of them are to my liking. My plan is to create a div that includes all the relevant content. My goal is to have a div at the bottom w ...

A convenient way to implement a polyfill for the Object.create method in JavaScript using

A new way to implement the polyfill for javascript Object.create() has left me puzzled. You can find the code here. if (typeof Object.create != 'function') { // Implementation steps based on ECMA-262, Edition 5, 15.2.3.5 // Reference: ...

Loading a unique shape using JSON within the KineticJS framework

Is there a way to load a unique custom shape using a Json file in Kinetic JS? The documentation I found only covers loading normal shapes. ...

Is there a way to host a Node.js application on a traditional web hosting platform like GoDaddy?

As an experienced JavaScript user/developer, I find myself struggling to understand how Node.js functions as a replacement for PHP. I have always used PHP for backend development, but now I want to transition to Node.js. The tutorials on Node.js confuse me ...

Angular 8 does not allow for the assignment of type '{}' to a parameter

I have a unique approach for managing errors: private handleErrors<T>(operation = 'operation', result?: T) { return (error: any): Observable<T> => { console.error(error); this.record(`${operation} failed: ${error.m ...

I will evaluate two arrays of objects based on two distinct keys and then create a nested object that includes both parent and child elements

I'm currently facing an issue with comparing 2 arrays of objects and I couldn't find a suitable method in the lodash documentation. The challenge lies in comparing objects using different keys. private parentArray: {}[] = [ { Id: 1, Name: &ap ...

modify the structure of an object according to specific conditions

So, I have this object that looks like the following. I'm currently working on restructuring the object based on the parent and child relationship. var b = []; for(var i=0;i<a.length;i++){ if(a[i].parent == null){ const children = a.filter(x => ...

Retrieve the currently displayed page on a bootstrap table

I'm currently utilizing the bootstrap table to showcase my data. One of the features I have added is a column with an edit button for each row. Upon clicking on the edit button, I open a bootstrap modal that displays the data from the corresponding ro ...

What is the best way to extract the ID from an event in TypeScript?

HTML Code: <ion-checkbox color="dark" checked="false" id="1on" (ionChange)="onTap($event)" ></ion-checkbox> TypeScript Code: onTap(e) { console.log(e); console.log(e.checked); } I am trying to retrieve the id of the checkbox. H ...

How can I prevent webpack from injecting eslint errors into my webpage?

Currently working with the Vue webpack project template and I've noticed that when the development server is running, any errors that occur are automatically injected into my webpage and also shown in the browser console. While I understand that this ...

Is the performance test conducted on the client side or server side?

Currently, I have an ASP.NET webforms website up and running. My intention is to conduct performance testing using the test tools in Visual Studio 2013 Ultimate edition. I have a rather fundamental question. Should the performance test be conducted from a ...

Handling null session values by converting them to empty strings in C# programming

When it comes to web programming, I am well-versed in using VB.net. Typically, I find myself doing something like this: Dim s as string = Session("s") Here, I retrieve a string value for s from the web session. If there is no value stored, I simply rece ...

Displaying the scope in HTML from a custom Angular directive: A step-by-step guide

Just getting started with angular js and I have a question. Is there a way to show the values of e.width and e.height in an HTML document? Can I utilize the scope within this context? .directive( "cropping", [function ($scope) { return { rest ...

Issue with displaying errors in vee-validate when using Vue.js Axios (More details provided)

When working on my Vue project, I encountered an issue while using Vee-Validate and Axios. During an API call to register a user, if the email is already in use, an error is thrown. To handle this error and display the error message, I used the following ...

What is the best way to turn off the annoying pop-up messages that show up for input validation, specifically the one that says "Please complete

Currently using Angular 2, my form has input fields similar to this simplified version: <input class="body-text1" type="text" [(ngModel)]="model.name" name="name" required minlength="1"> <!--more inputs like this --> Although I have implement ...

The SOAP proxy server is being contacted by an external application through IIS/ASP.NET

I am facing an unusual issue with a remote server (not controlled by me) that appends '.wsdl' to the URL string before calling a defined endpoint (). The server waiting for this request is no longer active, and I am looking to replace it with a & ...