I would like to fill a DataTable with the Page_Load event, then be able to access it from the ashx handler page when an Ajax call is sent from the client side. Currently, the DataTable is filled every time I make an Ajax call to the handler page, which makes it a bit on the slow side. Here's what I currently do:
Default.aspx.cs
public DataTable fillSCOMDTts()
{
//SCOM TableAdapter and DataTable
dsCIInfoTableAdapters.vManagedEntityTableAdapter taSCOM;
taSCOM = new dsCIInfoTableAdapters.vManagedEntityTableAdapter();
dsCIInfo.vManagedEntityDataTable dtSCOM = new dsCIInfo.vManagedEntityDataTable();
taSCOM.Fill(dtSCOM);
return dtSCOM;
}
Ajax call from client-side:
$.ajax({
url: '/FindFootprint.ashx?queryStr=' + strParameter,
dataType: 'json',
success: function (data) {
//do stuff
});
FindFootprint.ashx.cs
public void ProcessRequest(HttpContext context)
{
string strParameter = context.Request.QueryString["queryStr"];
bool binSCOMts = false;
Default d = new Default();
DataTable dtSCOMts = d.fillSCOMDTts();
var qstSCOMts = (from row in dtSCOMts.AsEnumerable()
let fieldName = row.Field<string>("DisplayName")
where fieldName.ToLower().Contains(strParameter)
select fieldName).ToArray();
if (qstSCOMts.Length > 0)
{
binSCOMts = true;
}
JsonObject JO = new JsonObject();
JO.Add("assetName", strParameter);
JO.Add("inSCOMts", binSCOMts.ToString());
context.Response.ContentType = "text/plain";
context.Response.Write(JO.ToString());
}
A handler is not really supposed to know anything about code/objects outside of itself.
If you're able to not use the handler in this case then you could set a private static DataTable MyTable; in your page.
Then on your page_load populate this static property.
You should then be able to access this property inside a web method that you call from you Ajax. The web method would be part of your pages code-behind so will have access to the private property set above. Put the code from your handler into this web method - bar the binding.
Related
I'm calling a webService.asmx using Jqueryand inside that service i'm retrieving a usercontrolcontrol's values to save them in the database but the user control has thrown a NullReferenceException
here is Ajaxcall
function SaveEdit()
{
$.ajax({
type: "POST",
url: "Services/RatiosSettingsService.asmx/UpdateRatios",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) { }
});
}
and this is WebServicecode
[WebMethod]
public void UpdateRatios()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Crs2"].ConnectionString))
{
ADO ado = new ADO();
List<SqlParameter> parameters = new List<SqlParameter>();
ucOtherRatios2 obj = new ucOtherRatios2();
Dictionary<string, int> hs = obj.GetHsChks();
foreach (KeyValuePair<string, int> item in hs)
{
SqlParameter para = new SqlParameter(item.Key, item.Value);
parameters.Add(para);
}
con.Open();
ado.CUDSp("UpdateRatios", "spUpdateClientRatios",parameters,con);
con.Close();
}
}
and here is where the exception happened inside usercontrol method that retrieve the controls values
public Dictionary<string, int> GetHsChks()
{
Dictionary<string, int> chks = new Dictionary<string, int>();
chks.Add("#siAnalysisOtherRatiosHistorical1", Convert.ToInt32(chkOthWcHs.Checked));
chks.Add("#siAnalysisOtherRatiosHistorical2", Convert.ToInt32(chkOthWiHs.Checked));
chks.Add("#siAnalysisOtherRatiosHistorical3", Convert.ToInt32(chkOthTlgHs.Checked));
chks.Add("#siAnalysisOtherRatiosHistorical4", Convert.ToInt32(chkOthEiHs.Checked));
chks.Add("#siAnalysisOtherRatiosHistorical5", Convert.ToInt32(chkOthEcHs.Checked));
chks.Add("#siAnalysisOtherRatiosHistorical6", Convert.ToInt32(chkOthEicHs.Checked));
chks.Add("#siAnalysisOtherRatiosHistorical7", Convert.ToInt32(chkOthEsHs.Checked));
chks.Add("#siAnalysisOtherRatiosHistorical8", Convert.ToInt32(chkOthEtHs.Checked));
return chks;
}
it says that checkbox is null
You can't access page's controls from a webmethod.
Since web methods don't carry the page state. It isn't a full postback. Instead just the session cookie travels with the request. You have to do a full page postback to get or set the control values.
Or you have to send the values of the controls through AJAX post method.
You can get more details on below link:
How to access page controls inside a static web method?
I see one thing in jQuery what would be good to change. Maby is better to use $.getJSON() function inside jQuery if you only getting JSON data. There you can use .done() to get data and .fail() for debbug.
Next thing is setup POST or GET variables to pass data to your JSON file to get proper data.
I am trying to get access a drop-down that is in aspx page from static web method but it seems i can't get access and not what am i doing wrong. I want to set the dropdown index value to -1. thanks
this is what i am trying to do:
[System.Web.Services.WebMethod]
public static void Cancel()
{
myDDL.SelectedIndex = -1;
}
here is the javascript call
<script type="text/javascript" language="javascript">
function Func() {
//alert("hello!")
var result = confirm('WARNING');
if (result) {
//click ok button
PageMethods.Delete();
}
else {
//click cancel button
PageMethods.Cancel();
}
}
</script>
I am trying to get access a drop-down that is in aspx page from static web method
the web method in asp.net page are static, this mean are executed without page context(not completely true, you can access to Session), so what you need its retrieve result from web method, then make your update client side, something like(not tested, sorry):
jQuery.ajax({
url: 'callAJAX.aspx/Cancel',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var result = data.d.result;
$('#yourDropDownID')[0].selectedIndex = result;
}
});
It should be myDDL.selectedIndex = -1;
You cannot access a control inside webmethod..At the web service method level you cannot see anything about the page structure..
You can try this code for clearing dropdown..
Instead of calling pagemethod Cancel you can clear it inside javascript function itself..
var ddl = document.getElementById('myDDL');
ddl.options[ddl.selectedIndex] = 0;
Refer this link for extra reading..
I have a Table object that I have created and populated in my code behind. It had to be done this way for various reasons.
I call a WebMethod via AJAX from the client side to send a variable from a dropdown list and then the table gets populated in a static method in the code behind. I need to get the Table into an ASP.Net PlaceHolder. I cannot call a PlaceHolder from a static method.
Instead of using an ASP.NET AJAX Page Method to return the data from your client-side AJAX call, try using an ASP.NET HTTP Handler, because it will allow you to better control the content coming back via HTTP headers instead of having to encode the result of the ASP.NET AJAX Page Method call, like this:
public class GetHtmlHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// Grab the drop down list variable value from the query string
// Use controls to build table or do it via StringWriter
// Create a table row with three cells in it
TableRow theTableRow = new TableRow();
for (int theCellNumber = 0; theCellNumber < 3; theCellNumber++)
{
TableCell theTableCell = new TableCell();
tempCell.Text = String.Format("({0})", theCellNumber);
theTableRow.Cells.Add(theTableCell);
}
// Create writers to render contents of controls into
StringWriter theStringWriter = new StringWriter();
HtmlTextWriter theHtmlTextWriter = new HtmlTextWriter(theStringWriter);
// Render the table row control into the writer
theTableRow.RenderControl(theHtmlTextWriter);
// Return the string via the StringWriter
context.Response.Write(theStringWriter.ToString());
}
public bool IsReusable
{
get
{
return false;
}
}
}
Now on the client-side, use the jQuery .ajax() function to call the HTTP Handler, like this:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "PATH_TO_HANDLERS/GetHtmlHandler.ashx?id=YOUR_DROP_DOWN_VALUE",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
// Select the placeholder control by class here and put HTML into it
$('.ThePlaceHolder').html(result);
}
});
});
Note: The above selector requires that you add a CssClass attribute to your PlaceHolder control, like this:
<asp:PlaceHolder id="PlaceHolder1" runat="server" CssClass="ThePlaceHolder" />
UPDATE:
Instead of using the class name in your jQuery selector, you can use the ID of the PlaceHolder, I had originally advised against this, because it is subject to name mangling when using master pages in ASP.NET. At any rate, there is the ClientIDMode attribute which you can use, like this:
<asp:PlaceHolder id="PlaceHolder1" runat="server" ClientIDMode="Static" />
Now your jQuery selector would look like this:
// Select the placeholder control by ID here and put HTML into it
$('#<%= PlaceHolder1.ClientID %>').html(result);
Note: I prefer to avoid the angle bracket (<%= %>) notation where possible.
I am working on ASP.net MVC 2.0 Application. I am using Ajax form. In that I have a dropdown and a button.
After clicking on button, i wanted to reload the dropdown if the Ajax request is sucessful.
So, i am calling a jquery Ajax function inside the callback function of the Ajax form.
In that jquery Ajax function, I am writing code to get the new data and binding to drop down so that it will be reloaded with new data.
Here, Every thing is working fine for the first time. But, when i click the button for the next time, the Ajax jquery function is called but it is not hitting contoller action method.
Code:
Here, are my jquery functions:
<script type="text/javascript">
function GetData() {
$.getJSON("/Home/GetUsers", null, function (data) {
var selectList = $("#ddlUsers");
selectList.empty();
alert("Inside Get Json method of jquery Ajax");
var defaultoption = $('<option>').text("--Select--").val("");
selectList.append(defaultoption);
$.each(data, function (index, optionData) {
var option = $('<option>').text(optionData.Text).val(optionData.Value);
alert(option);
selectList.append(option);
});
});
}
function Callback() {
GetData();
alert("Sucessfully done");
}
function Failed() {
alert("Sorry, an error occured while processing your request");
}
Methods inside Contoller:
[HttpGet]
public JsonResult GetUsers() ----> Method that is called from GetData() Ajax call
{
var data = GetUsersList();
return Json(data, JsonRequestBehavior.AllowGet);
}
public SelectList GetUsersList()
{
Db Fectch
return data;
}
I am unable to understand why the above indicated method is not called for second time yet the GetData() is called.
Please help..
I think it's the cache, try adding this line before your controller method:
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
You can also place this line at the top of the controller, if you want it to be applied to all methods.
I have two asp:BulletedLists, one is populated on Page_Load and the other is empty. The user can drag and drop < li >'s between them, the meat of that drag-n-drop is
function Move(element, source, target) {
var newLI = document.createElement("li");
var sourceBL = document.getElementById(source);
var targetBL = document.getElementById(target);
newLI.innerHTML = element.innerHTML;
sourceBL.removeChild(element);
targetBL.appendChild(newLI);
}
I create a new element so that it aligns itself within the asp:BulletedList rather than placing itself where the mouse is released.
The problem is I need to know what is where on postback, the second asp:BulletedList is always empty and the first asp:BulletedList populates itself with the original values even though I do not clear or repopulate them.
foreach (ListItem li in blSelectedDocuments.Items) // .Items is empty
{
}
In the past with working with jQuery plugins on ASP.NET WebForms pages, I have used AJAX to send the updated data back to an ASP.NET AJAX Page Method and then stored the changes into Session cache. Then upon postback, the Page_Load would look into the Session to see what order the values in the list were (I had a drag and drop list for the order of display of a report).
Mock code example:
JavaScript:
function Move(element, source, target) {
var newLI = document.createElement("li");
var sourceBL = document.getElementById(source);
var targetBL = document.getElementById(target);
newLI.innerHTML = element.innerHTML;
sourceBL.removeChild(element);
targetBL.appendChild(newLI);
// TODO: Serialize source and target lists to JSON to pass to the server
var serializedData = {};
// Use jQuery.ajax() to call ASP.NET AJAX Page Method
$.ajax({
type: "POST",
url: "PageName.aspx/UpdateListsInSessionCache",
data: serializedData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something here when the AJAX calls completes
}
});
}
ASP.NET Code-behind (C#)
using System.Web.Services;
[WebMethod]
public static void UpdateListsInSessionCache(List<ListItem> source, List<ListItem> target)
{
Session["SourceList"] = source;
Session["TargetList"] = target;
}
protected void Page_Load(object sender, EventArgs e)
{
// Create new lists so we have something empty and not null to work with
var source = new List<ListItem>();
var target = new List<ListItem>();
// Always check for values in Session cache and update if there are values
if (Session["SourceList"] != null)
{
source = Session["SourceList"] as List<ListItem>;
}
if (Session["TargetList"] != null)
{
target = Session["TargetList"] as List<ListItem>;
}
// Do something with source and target lists
}
Horrifically, none of that worked. I'm on SharePoint and the Session wasn't enabled (or whatever) because of some deep dark corner of SharePoint that the asp.config file is located in. Neither did ViewState work in the similar manner. Maybe the AJAX half of that would have worked, but I never got that far.
The solution I got to work was to create a hidden input field, write the order of the asp:BulletedList to that hidden field to go with the postback via the Submit button. Thanks JasonP for serialisation fiddle.
NOTE: I tried some other suggestions I found on the web, using a Label/TextBox with ViewState and/or Readonly properties set did not work for me. Label worked to change text within the page but did not persist on postback.