stop old session list object to add up - asp.net

what my code 'below' does is: the client javascript calls a webservice method which creates a generic list and then stores it into a session.
[WebMethod(EnableSession = true)]
public void SaveUserSelection(string slctdRooms, string slctdcst)
{
List<SelectRms> SelectR = Session["someinfo"] as List<SelectRms>;
if (SelectR == null)
{
SelectR = new List<SelectRms>();
Session["someinfo"] = SelectR;
}
SelectR.Add(new SelectRms { roomtype = slctdRooms, Roomcst = slctdcst });
}
I would then retreave the session to show the data in another page like this
List(SlctdRmWebSrv.SelectRms) SelctdRM = (List(SlctdRmWebSrv.SelectRms))Sessio["someinfo"];
if(SelctdRM != null)
{
repeater1.DataSource = SelctdRM;
repeater1.DataBind();
}
the problem is that every time I retreave the session to create a new list, the new data is added up to the old one. I want to have a situation where only the current data is displayed. I tried to clear the list, abandon the session, or clear the repeater before adding the new ones it did hehlp; easy there an easy way to get this done. many thanks

It sounds like you are calling SaveUserSelection multiple times from your javascript. If that's the case then only the very first time your list will be initialized.
Therefore, your list will keep adding stuff to the "old" list since the list has not been cleared or re-initialized .
You should probably put the initialization in a separate method (either on Page_Load or create a new WebMethod just to clear/initialized the list). For example, this is how it looks if you decide to put it on the Page_Load event:
Note: code no tested
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
Session["someinfo"] = new List<SelectRms>();
}
This is how it looks if you create a WebMethod:
[WebMethod(EnableSession = true)]
public void InitUserSelection()
{
Session["someinfo"] = new List<SelectRms>();
}
Call this method when you are ready to keep track of the user selection. Perhaps when your form initially loads (place this script at the bottom of the page):
$(document).ready(function() {
$.ajax({
type: "POST",
url: "PageName.aspx/InitUserSelection",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// After init you could use this method to do something else
}
});
});
So SaveUserSelection will look like this:
[WebMethod(EnableSession = true)]
public void SaveUserSelection(string slctdRooms, string slctdcst)
{
List<SelectRms> SelectR = Session["someinfo"] as List<SelectRms>;
if (SelectR != null)
SelectR.Add(new SelectRms { roomtype = slctdRooms, Roomcst = slctdcst });
}
And this is how your javascript looks like whenever your selection changes:
$.ajax({
type: "POST",
url: "PageName.aspx/SaveUserSelection",
data: "{'slctdRooms':'Value1','slctdcst':'Value2'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
//your list was updated, you may do something afterwards
}
});

#Ulises. this is what I ma doing:
public List<SelectRms> GetUserContent()
{
List<SelectRms> SelectR=new List<SelectRms>();
Session["someinfo"] = SelectR;
return Session["someinfo"] as List<SelectRms>;
}
[WebMethod(EnableSession = true)]
public void SaveUserSelection(string slctdRooms, string slctdcst)
{
List<SelectRms> SelectR = GetUserContent();
SelectR.Add(new SelectRms { roomtype = slctdRooms, Roomcst = slctdcst });
}
But instead it returns a single (first) element of my list rather than the whole list, Any Help

Related

Export to excel not working from HttpHandler J-Query AJAX

im have a weird problem whereby my functionality of exporting to excel doesnt seem to work.
im using J-Query and AJAX to pass html data to a http handler which has some simple context.Response code which all seems fine. Anyway, heres my code:
// my hyperlink for user to click
Click Here to Export
my J-Query/AJAX code
<script type="text/javascript">
$(document).ready(function () {
$("#hyperLink").click(function (e) {
var result = $('#output').html();
var newRes = result.replace('\n', '');
$.ajax({
url: "ExportToExcelhandler.ashx",
data: { 'htmlData': newRes },
dataType: "json",
type: "POST",
success: function (data) {
alert(data);
}
});
});
});
</script>
and my handler:
public void ProcessRequest(HttpContext context)
{
string htmlStuff = context.Request["htmlData"];
string trimStart = "";
string trimEnd = "";
if (htmlStuff != null)
{
trimStart = htmlStuff.Substring(75, htmlStuff.Length - 75);
trimEnd = trimStart.Remove(trimStart.Length - 8, 8) + "";
}
string final= trimEnd;
context.Response.Clear();
context.Response.Buffer = true;
context.Response.AddHeader("content-disposition", "attachment; filename=excelData.xls");
context.Response.ContentType = "application/vnd.ms-excel";
HttpResponse response = context.Response;
context.Response.Output.Write(finalHtmlData);
context.Response.Flush();
context.Response.End();
}
-- Granted, I'm doing some weird things with replace function in my J-Query, and Substring and Remove in my handler; this is because i had to trim my html data so that only the table with the data inside it was included (caused error otherwise). The html data is just report data. So the html data is passed fine to the handler, and it goes through the ProcessRequest method fine, yet doesn't export to excel. Any help would be greatly appreciated, thanks.
Split this into two HTTP handlers, one to generate the Excel data and the second to retrieve the data and have a resource point at it, like this:
GenerateExcelDocument HTTP handler code:
public void ProcessRequest(HttpContext context)
{
string htmlStuff = context.Request["htmlData"];
var docIdentifier = this.GenerateExcelDocument(htmlStuff);
context.Response.ContentType = "text/plain";
context.Response.Write(docIdentifier.ToString("N"));
}
private Guid GenerateExcelDocument()
{
var identifier = Guid.NewGuid();
string trimStart = "";
string trimEnd = "";
if (htmlStuff != null)
{
trimStart = htmlStuff.Substring(75, htmlStuff.Length - 75);
trimEnd = trimStart.Remove(trimStart.Length - 8, 8) + "";
}
// Logic that generates your document and saves it using the identifier
// Can save to database, file system, etc.
return identifier;
}
Now you can call this HTTP handler, like this:
$(document).ready(function () {
$("#hyperLink").click(function (e) {
var result = $('#output').html();
var newRes = result.replace('\n', '');
$.ajax({
url: "GenerateExcelDocument.ashx",
data: { 'htmlData': newRes },
dataType: "json",
type: "POST",
success: function (result) {
window.location.href = '/RetrieveExcelDocument.ashx/' + result;
}
});
});
});
Note: The success callback is where you can hook up the HTML resource to the file retrieval from the server (think href of the anchor tag that worked without passing data to the handler before).
Finally, we need to build the retrieval HTTP handler logic to actually get the Excel document, based upon the identifier returned from the GenerateExcelDocument HTTP handler call, like this:
RetrieveExcelDocument HTTP handler code:
public void ProcessRequest(HttpContext context)
{
var identifier = new Guid(context.Request.Url.Segments[1]);
// Get Excel document content from database, file system, etc. here
var fileContent = GetExcelDocument(identifier);
context.Response.AddHeader("content-disposition",
"attachment; filename=excelData.xls");
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.OutputStream.Write(fileContent, 0, fileContent.Length);
}

ASP.NET: How to update client-side from server side?

I want to update a label on client side from server side while the function is still under execution at server side. How can I achieve this?
Here's the code snippet:
protected void Button1_Click(object sender, EventArgs e)
{
string Result = "Success";
if (Result == "Success")
{
Label1.Text = "Plan mst Completed";
Thread.Sleep(2000); //Some functionality here
Label1.Text = "Packing date mst Started";
}
if (Result == "Success")
{
Label1.Text = "Packing date mst Completed";
Thread.Sleep(2000); //Some functionality here
Label1.Text = "Etd mst Started";
}
if (Result == "Success")
{
Label1.Text = "Etd mst Completed";
Thread.Sleep(2000); //Some functionality here
Label1.Text = "Inner box mst Started";
}
}
I want all changes in label1.text to be reflected on client side, while function is still under execution.
Please help!!!
Direct communication with the Front End from inside that method is going to be hard. Here's how I'd do it.
1) Split "Plan mst", "Packing date mst", "Etd mst", and "Inner box mst" into 4 separate functions.
2) Have the button click event on the page fire a JavaScript function to hit each of the 4 methods, one after the other, via AJAX. Make up a new ASPX page for each function ("InnerBox.aspx", etc). If you have jquery, it would look something like this:
$("#SubmitButton").click(function () {
DoPlanMst();
});
function DoPlanMst(argumentObj) {
SetLabel("Plan MST Started");
$.ajax({
url: "PlanMst.aspx",
type: "POST",
data: argumentObj, // your post params
success: function () {
SetLabel("Plan MST Completed");
DoPackingDateMst();
}
});
}
function DoPackingDateMst(argumentObj) {
SetLabel("Packing Date MST Started");
$.ajax({
url: "PackingDate.aspx",
type: "POST",
data: argumentObj, // your post params
success: function () {
SetLabel("Packing Date MST Completed");
DoEtdMst();
}
});
}
function DoEtdMst(argumentObj) {
SetLabel("ETD MST Started");
$.ajax({
url: "EtdMst.aspx",
type: "POST",
data: argumentObj, // your post params
success: function () {
SetLabel("ETD MST Completed");
DoInnerBoxMst();
}
});
}
function DoInnerBoxMst(argumentObj) {
SetLabel("Inner Box MST Started");
$.ajax({
url: "InnerBoxMst.aspx",
type: "POST",
data: argumentObj, // your post params
success: function () {
SetLabel("Inner Box MST Completed");
}
});
}
function SetLabel(message) {
$("#Label1").val(message);
}
If you don't want 4 sep ASPX pages, that's fine. You can roll them into a single file called "ProcessMSTs.aspx" that looks for a query string param to determine the method in its code behind to call, while still passing in POST params.
EDIT: fixed a typo in the function names in the success function of the AJAX calls.
how are you calling this function from the browser.Is it an asynchronous call then you can manage that in client side it self. if it is an synchronous one then it will not be possible as your response to you request is still pending.
use this
Jquery Ajax post animation during ajax process?

selecting all the records from the database using jquery ajax in asp.net

i want to generate the table of contents from database.. using jquery ajax in asp.net, i am using sql server 2008 as a backend. for this i created a webmethod in my normal aspx page. and on the clientside wrote the ajax script to fetch records but when i loop through the results, i gets message undefined and nothing happens.. i want to generate table out of the records from database below is my webmethod.
[WebMethod]
public static Poll[] GetPollDetailed()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("sp_SelectQuestion", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.AddWithValue("#siteid", 3);
DataTable dt = new DataTable();
da.Fill(dt);
List<Poll> _poll1 = new List<Poll>();
foreach (DataRow row in dt.Rows)
{
Poll _poll = new Poll();
_poll.QuestionID = Convert.ToInt32(row["questionID"]);
_poll.Question = row["question"].ToString();
_poll.Published = Convert.ToInt32(row["visible"]);
_poll.Date = Convert.ToDateTime(row["Added_Date"]);
}
return _poll1.ToArray();
}
public class Poll
{
public Poll() { }
private int _questionId, _published;
private string _question;
private DateTime _date;
public int QuestionID
{
get { return _questionId; }
set { _questionId = value; }
}
public string Question
{
get { return _question; }
set { _question = value; }
}
public DateTime Date
{
get { return _date; }
set { _date = value; }
}
public int Published
{
get { return _published; }
set { _published = value; }
}
}
</code>
and below is my script.
<code>
$(this).load(function () {
$.ajax({
type: "POST",
url: "AddPollAJax.aspx/GetPollDetailed",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
for (i = 0; i < data.length; i++) {
alert(data[i].QuestionID);
}
},
error: function (data) {
alert("Error: " + data.responseText);
}
});
});
</code>
can any one please help me to resolve this issue, i am very curious about it.
Assuming your service is configured correctly to return JSON data, issue lies at your js code fragment for success callback i.e.
success: function (data) {
for (i = 0; i < data.length; i++) {
alert(data[i].QuestionID);
}
},
MS ASP.NET script services always return a wrapped JSON due to security issues, so you need unwrap resultant JS object to get the actual data. So you need to change the code to
success: function (result) {
var data = result.d; // actual response will be in this property
for (i = 0; i < data.length; i++) {
alert(data[i].QuestionID);
}
},
BTW, ASP.NET Web Services are now considered legacy, so I will suggest you to migrate to WCF services instead.

Get data from aspx.cs page to aspx page

So I am using a jquery plug in that allows me to change the order of things in a list by dragging and dropping them.
So my goal is to be able to grab a list of my objects (AlertInfo) and using it in a javascript function.
I was able to use a json webservice call in a test project to pass the data to the page.
But we don't have a webservice page now so I tried to grab it from a aspx.cs page and it hasn't worked.
///Aspx page:
$.ajax({
type: "POST",
url: "~/Alerts/GetAlerts",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var data = eval("(" + msg.d + ")");
jQuery.each(data, function (rec) {
AlertList[AlertList.length] = new objAlert(this.id, this.title, this.details, JSONDateSerializationFix(this.startdate), JSONDateSerializationFix(this.enddate));
UpdateDisplayList();
})
},
error: function (msg) {
alert("BRAD" + msg);
}
The issue is that the Alerts page in "URL /Alerts/GetAlerts" is Alerts.aspx.cs. I can't figure out if I can use this ajax command to call a method in a aspx.cs page.
//Code behind page aspx.cs
[WebMethod]
//[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetAlerts()
{
List<AlertInfo> list = AlertInfo.GetTestAlerts();
return new JavaScriptSerializer().Serialize(list);
}
public List<AlertInfo> GetAlertsList()
{
List<AlertInfo> list = AlertInfo.GetTestAlerts();
return list; ;
}
So I was hoping that I could load data into an asp control (dataList) and then grab the data
//code behind page
protected void Page_Load(object sender, EventArgs e)
{
dataListAlertList.DataSource = GetAlertsList();
dataListAlertList.DataBind();
}
public static List<AlertInfo> GetTestAlerts()
{
List<AlertInfo> list = new List<AlertInfo>();
list.Add(new AlertInfo("0", "Alert 1 Title", "Alert 1 Detail", "10/10/2010", "10/10/2011"));
list.Add(new AlertInfo("1", "Alert 2 Title", "Alert 2 Detail", "10/10/2010", "10/10/2011"));
return list;
}
//.aspx page
$(document).ready(function () {
var a1 = $("#dataListAlertList").val();
// do fun stuff now.
}
But I keep getting undefined....
Didn't need to preload. Ended up using the datalist and then changed how it was formatted. In the document ready function I grabbed the divs and applied the properties that needed to be set.

Access to QueryString / Session from a static Method?

I use ASP.Net and a static WebMethod / PageMethod to do some async work.
My question is how to access my queryStrings and Session variables here?
I tried "HttpContext.Current" and a lot of information is available here, but not my QueryString nor my Session and I don't know why.
[WebMethod(EnableSession=true)]
public static object Update(string time)
{
string timer;
string lastBidder;
string price;
//Countdown timer
DateTime dt = DateTime.Parse(time);
dt = dt.AddSeconds(-1.0);
timer = dt.ToString("HH:mm:ss");
int auctionID = 6;
if (!int.TryParse(HttpContext.Current.Request.QueryString["id"], out auctionID))
throw new Exception("Seitenaufruf ohne ID");
Business.AuctionHandling ah = new Business.AuctionHandling();
DAL.Auktion auktion = ah.GetSingleAuction(auctionID);
price = auktion.AktuellerPreis.ToString("###0.00");
//this.gvHistory.DataBind();
List<DAL.Biethistorie> his = ah.GetBidHistoryForAuction(auctionID);
if (his.Count > 0)
{
lastBidder = his[0].Benutzer.Benutzername;
//History fett
//gvHistory.Rows[0].Font.Bold = true;
//gvHistory.Rows[0].ForeColor = System.Drawing.ColorTranslator.FromHtml("#3B4D5F");
//lblHöchstesGebot.ForeColor = System.Drawing.Color.Black;
}
else
{
lastBidder = Helper.StringHelper.AuctionDeatil_NoBidder;
//lblHöchstesGebot.ForeColor = System.Drawing.Color.Red;
}
return new
{
valueTimer = timer,
valuePrice = price,
valueLastBidder = lastBidder
};
}
The QueryString is in the Request property.
System.Web.HttpContext.Current.Request.QueryString
But the Session is in there:
System.Web.HttpContext.Current.Session
Out of interest why aren't you just passing the information you need to the web method as you are calling it?
I had a similar problem. I had a number of static methods I was using to help manage my Cache and Session. Luckily, you can pass a reference to the Cache or Session into your moethods like this:
public static void DoSomething(System.Web.SessionState sessn)
And then access your session by using the sessn object.
THIS IS LATE REPLY BUT WILL HELP OTHERS AND MARK IT AS ANSWER ..well u have to post your code on how you are calling that Update method. coz i am doing the same and im getting my querystring and the trick for that is you have to pass that in alongwith your get or post call like following
$.ajax({
type: "POST",
url: "" + getDirectoryPath() + getCurrentPageName() + "/SavePatientEpisodes?ApplicationInstanceID=" + querystring,
data: JSON.stringify({ PatientOne: patientOneData, PatientTwo: patientTwoData, PatientOneID: $("#tbPatient1").val(), PatientTwoID: $("#tbPatient2").val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
}
});
AND ACCESS IT as BELOW
_
Public Shared Function SavePatientEpisodes(ByVal PatientOne As List(Of Episode), ByVal PatientTwo As List(Of Episode), ByVal PatientOneID As String, ByVal PatientTwoID As String) As String
Dim dd As String = HttpContext.Current.Request.QueryString("ApplicationInstanceID")
Dim lang As Integer = toInt(HttpContext.Current.Session("UserID"))
return ""
End Function

Resources