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.
Related
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);
}
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?
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
first of all apologies for my english.
I'm a newby in json area.
My problem is that i can't parse the data recived in a json response into a asp:LinkButton or whatever asp:element, coz i can't create a correct sintax.
Especifically, What I'm trying to do, is this:
<script type="text/javascript">
$.getJSON("http://www.carqueryapi.com/api/0.3/?callback=?", { cmd: "getMakes", min_year:"1941", max_year:"2012"}, function (data) {
var makes = data.Makes;
for (var i = 0; i < makes.length; i++) {
($("<asp:LinkButton ID=\"lb" + i +"\" runat=\"server\" />").text(makes[i].make_display )).appendTo("#lbProva");
}
});
<script>
<ul id="lbProva" class="lb_prova" >
</ul>
I hope that someone could help me coz i've tryed many possibilities but no one was the right one.
Thank u in advance.
You can't create asp.net server controls in javascript on client side. If you want to use json data on client side, you must apply it to already generated html controls.
Actually, you can create server controls only on a server. So the question is how to pass AJAX call response to server and enforce it to refresh desired area on a page.
First variant
<script type="text/javascript">
$(function () {
$.getJSON("http://www.carqueryapi.com/api/0.3/?callback=?", { cmd: "getMakes", year: "2009" },
function (data) {
//The 'data' variable contains all response data.
var makes = $.map(data.Makes, function (make) { return make.make_display; }).join(";");
document.getElementById("<%= CarMakersHiddenField.ClientID %>").value = makes;
__doPostBack("<%= CarMakersUpdatePanel.ClientID %>", "");
});
});
</script>
<asp:UpdatePanel runat="server" ID="CarMakersUpdatePanel" UpdateMode="Conditional">
<ContentTemplate>
<asp:HiddenField runat="server" ID="CarMakersHiddenField" />
<asp:BulletedList runat="server" ID="MakersList" DisplayMode="LinkButton">
</asp:BulletedList>
</ContentTemplate>
</asp:UpdatePanel>
Server code:
protected void Page_Load(object sender, EventArgs e)
{
MakersList.Items.Clear();
foreach (var maker in CarMakersHiddenField.Value.Split(';'))
{
MakersList.Items.Add(maker);
}
}
Second approach is more siutable if you need to pass to server some complex object like array of makers objects. In that case you can serialize this object to JSON string on client and deserialize it on server. Looks like previous version with bit changes:
<script type="text/javascript">
$(function () {
$.getJSON("http://www.carqueryapi.com/api/0.3/?callback=?", { cmd: "getMakes", year: "2009" },
function (data) {
//The 'data' variable contains all response data.
var serializedString = Sys.Serialization.JavaScriptSerializer.serialize(data.Makes);
document.getElementById("<%= CarMakersHiddenField.ClientID %>").value = serializedString;
__doPostBack("<%= CarMakersUpdatePanel.ClientID %>", "");
});
});
</script>
Markup left the same as in the first version.
Server code:
[Serializable]
public class Make
{
public string make_id;
public string make_display;
public bool make_is_common;
public string make_country;
}
protected void Page_Load(object sender, EventArgs e)
{
MakersList.Items.Clear();
if (!String.IsNullOrEmpty(CarMakersHiddenField.Value))
{
var serializer = new DataContractJsonSerializer(typeof(Make[]));
using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(CarMakersHiddenField.Value)))
{
var makes = serializer.ReadObject(stream) as Make[];
if (makes != null)
{
foreach (var maker in makes)
{
MakersList.Items.Add(new ListItem(maker.make_display, maker.make_id));
}
}
}
}
}
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.