How to access WebMethod Session value in another page using jQuery Ajax in ASP.Net

Last Reply 8 months ago By AnandM

Posted 8 months ago

 default1.aspx page-

[WebMethod(EnableSession=true)]
public static void createdb(string dbname)
{

 HttpContext.Current.Session["database"] = dbname;

}

and i want to access and use session value to another page for instance default2.aspx

here is my code for retrieving session value

string sess_val = HttpContext.Current.Session["database"].ToString();

but  session is null

plz help me out

Posted 8 months ago
Hi @mohdImran,
Please try the following

Send DropDownList Selected Item Value to another Page using Session in ASP.Net

It might help you.

Cheers Andrea.

Posted 8 months ago

Hi mohdImran,

as per your explaination i have cross checked with code and its working fine and please let me know what exactly you are trying to do?


Posted 8 months ago Modified on 8 months ago

 This is my html coding where i am calling webmethod using jquery

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="database_reg.aspx.cs" Inherits="fleet.ajax.database_reg" %>
<div class="row">
    <div id="dialog" style="background-color: aliceblue;">
        <input id="txt_db_name" type="text" runat="server" />
        <label id="lbl_db" runat="server">
        </label>
    </div>
</div>
<style>
    .ui-dialog-titlebar-close
    {
        visibility: hidden;
    }
</style>
<script type="text/javascript">
      $(document).ready(function (){
          var dialogDiv = $('#dialog');
          dialogDiv.dialog({
              title: 'Please Enter Database Name',
              draggable: false,
              resizable: false,
              closeOnEscape: false,
              model: true,
              autoOpen: true,
              buttons: {
                  'Submit': createdb,
                  //'Cancel': function () {
                  //    dialogDiv.dialog('close');
                  //    clearInputFields();
                  //}
              }
          });
        
          function createdb() {
              //debugger
              var dbname = $('#txt_db_name').val();
              $.ajax({
                  url: 'ajax/database_reg.aspx/createdb',
                  method: 'post',
                  data: "{ dbname: '" + dbname + "'}",
                  contentType: 'application/json; charset=utf-8',
                  dataType: 'json',
                  success: function () {
                  }
              });
          }
      });
</script>

and this is my code behind where web method is definde and session also but problem is that i am unable to get session to another page.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Services;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System.Xml;
namespace fleet.ajax
{
    public partial class database_reg : System.Web.UI.Page
    {
        [WebMethod(EnableSession = true)]
        public static void createdb(string dbname)
        {
            String str;
            SqlConnection myConn = new SqlConnection("Data Source=xx.xx.xx.xx;Initial Catalog=master;User ID=sa;Password=xxxxx;");

            str = "CREATE DATABASE " + dbname + " ON PRIMARY " +
                  "(NAME = N'" + dbname + "', " +
                  "FILENAME = N'C:\\Program Files\\Microsoft SQL Server\\MSSQL10_50.MSSQLSERVER\\MSSQL\\DATA\\" + dbname + ".mdf', " +
                  "SIZE = 5MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
                  "LOG ON (NAME = N'" + dbname + "_log', " +
                  "FILENAME = N'C:\\Program Files\\Microsoft SQL Server\\MSSQL10_50.MSSQLSERVER\\MSSQL\\DATA\\" + dbname + "_log.ldf', " +
                  "SIZE = 1MB, " +
                  "MAXSIZE = 5MB, " +
                  "FILEGROWTH = 10%)";

            SqlCommand myCommand = new SqlCommand(str, myConn);
            try
            {
                HttpContext.Current.Session["database"] = dbname;
                myConn.Open();
                myCommand.ExecuteNonQuery();
                SqlConnection myConn1 = new SqlConnection("Data Source=xx.xx.xx.xx;Initial Catalog=" + dbname + ";User ID=sa;Password=xxxxxx;");
                myConn1.Open();
                FileInfo file = new FileInfo(System.Web.HttpContext.Current.Server.MapPath("script.sql"));
                string strscript = file.OpenText().ReadToEnd();
                string strupdatescript = strscript.Replace("[demo]", dbname);
                Server server = new Server(new ServerConnection(myConn1));
                server.ConnectionContext.ExecuteNonQuery(strupdatescript);
                myConn1.Close();
            }
            catch (System.Exception ex)
            {
                // MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                if (myConn.State == ConnectionState.Open)
                {
                    myConn.Close();
                }
            }

            bool isNew = false;
            string path = System.Web.HttpContext.Current.Server.MapPath("~/Web.Config");
            XmlDocument doc = new XmlDocument();
            doc.Load(path);
            XmlNodeList list = doc.DocumentElement.SelectNodes(string.Format("connectionStrings/add[@name='{0}']", dbname));
            XmlNode node;
            isNew = list.Count == 0;
            if (isNew)
            {
                node = doc.CreateNode(XmlNodeType.Element, "add", null);
                XmlAttribute attribute = doc.CreateAttribute("name");
                attribute.Value = dbname;
                node.Attributes.Append(attribute);
                attribute = doc.CreateAttribute("connectionString");
                attribute.Value = "";
                node.Attributes.Append(attribute);
            }
            else
            {
                node = list[0];
            }
            string conString = node.Attributes["connectionString"].Value;
            SqlConnectionStringBuilder conStringBuilder = new SqlConnectionStringBuilder(conString);
            conStringBuilder.InitialCatalog = dbname;
            conStringBuilder.DataSource = "xx.xx.xx.xx";
            conStringBuilder.UserID = "sa";
            conStringBuilder.Password = "mxxxx";
            node.Attributes["connectionString"].Value = conStringBuilder.ConnectionString;

            if (isNew)
            {
                doc.DocumentElement.SelectNodes("connectionStrings")[0].AppendChild(node);
            }
            doc.Save(path);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }
    }
}

 


Posted 8 months ago

Hi mohdImran,

I have a created a sample which full fill your requirement.

You need to modify according to your requirement.

Default.aspx

<div id="dialog" style="background-color: aliceblue;">
    <input id="txt_db_name" type="text" runat="server" />
    <label id="lbl_db" runat="server">
    </label>
</div>
<div>
    <style>
        .ui-dialog-titlebar-close
        {
            visibility: hidden;
        }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
    <link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css"
        rel="stylesheet" type="text/css" />
    <script type="text/javascript">
        $(document).ready(function () {
            var dialogDiv = $('#dialog');
            dialogDiv.dialog({
                title: 'Please Enter Database Name',
                draggable: false,
                resizable: false,
                closeOnEscape: false,
                model: true,
                autoOpen: true,
                buttons:
        {
            'Submit': createdb
        }
            });
        });

        function createdb() {
            var dbname = $('#txt_db_name').val();
            $.ajax({
                url: 'Default.aspx/createdb',
                type: 'POST',
                data: "{dbname: '" + dbname + "'}",
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function () {
                    window.location.href = 'Default2.aspx';
                }
            });
        }      
    </script>
</div>

Default.aspx.cs

[WebMethod(EnableSession = true)]
public static void createdb(string dbname)
{
    HttpContext.Current.Session["database"] = dbname;
}

Default2.aspx

<div>
    <asp:Label ID="lblSessionData" runat="server" />
</div>

Default2.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(Session["database"].ToString()))
    {
        lblSessionData.Text = Session["database"].ToString();
    }
    else
    {
        lblSessionData.Text = "Empty Session Data.";
    }
}

ScreenShot

I agree, here is the link: https://www.e-iceblue.com/Introduce/spire-office-for-net-free.html