Value passed by ajax from Javascript to C#, Replied but not saved - javascript

I pass a value to my C# part with ajax and I get a response back. But I can't save the value or use it in my C# code. More information below:
Ajax Call: (gallery.aspx)
$.ajax({
url: Url, //assigned previously
data: 'call=ajax&method=GetList&typeIds=' + typeIds.replace(",",""),
type: 'POST',
dataType: 'json',
success: function (resp) {
console.log("From AJAX: " + resp) // this works and shows the result
},
error: function (xhr, status) {
console.log("Sorry, there was a problem!");
}
});
Code Behind (CodeFile):(gallery.aspx.cs)
Update: Full C# code snippet
public partial class gallery : System.Web.UI.Page
{
public List<string> images = new List<string>();
public List<string> imagesList = new List<string>();
public List<string> filteredImagesList = new List<string>();
public List<string> testList = new List<string>();
protected string imagesName;
protected string filterType;
protected void Page_Load(object sender, EventArgs e)
{
if (Request["call"].ParseString() == "ajax")
{
Response.Write(Request["typeIds"].ParseString().TrimEnd(','), true, ResponseType.Json);
filterType = Request["typeIds"].ParseString().TrimEnd(',');
}
else
{
filterType = "Not Assigned!";
}
}
}
Output on the page: Not Assigned!
Meaning <h1><%=filterType%></h1> in aspx file returns the else statement from aspx.cs file
But I get the response back in my javascript while console.log("From AJAX: " + resp) shows the result.
BUT I can't use filtertype's value in my c# codefile.
I can't understand how come the Response.Write(Request["type"].ParseString().TrimEnd(','), true, ResponseType.Json); gives back the Request["type"] to js part but don't save it for my codefile. Should it be anything like Response.Read or Response.Save or something?
Does someone know what is going on in here?

You can store the ajax response in a hidden field and then access that hidden field value in server side code.
<asp:HiddenField ID="HiddenField1" runat="server" />
$.ajax({
url: Url, //assigned previously
data: 'call=ajax&method=GetList&type=' + typeIds.replace(",",""),
type: 'POST',
dataType: 'json',
success: function (resp) {
console.log("From AJAX: " + resp) // this works and shows the result
$('#<%=HiddenField1.CliendId%>').val(resp);
},
error: function (xhr, status) {
console.log("Sorry, there was a problem!");
}
});
You can then access in server side code like this:
HiddenField1.Value

OK. It will never be assigned in the way how you did it. Simply because when the page is loading and all controls are rendering no ajax calls are taking into account Page Life Cycles. Because of that on page load filterType is not assigned.
Although you have a couple of options
Use Ajax with update panel and PageRequestManager class
Change the value through JQuery or Vanilla JS by using <%=filterType.ClientID%>
If you need only front-end representation you can use either option. If you need it for further back-end I'm afraid option 1 only choice for you.

Related

AJAX indicates that WEBMETHOD was successful, but it never actually triggers the webmethod on code behind

I've been through countless posts and cant figure out what I am doing wrong. I have a asp.net website with C# code behind. In it, I need for a javascript function on the .aspx page to trigger a method on the aspx.cs page. I wrote the following code:
.aspx page (my ScriptManager):
</head>
<body id="bodycontainer">
<asp:ScriptManager ID="ScriptManager2" runat="server" EnablePartialRendering="false" EnablePageMethods="true"/>
The Javascript function using ajax on the .aspx page:
function ValidateForm() {
$.ajax({
type: "POST",
url: "default.aspx/Save",
data: {},
contentType: "application/json; charset=utf=8",
// dataType: "json", // NOT NEEDED IF NO RETURN VALUE
async: true, // OPTIONAL
success: function (msg) {
alert("success");
},
error: function (msg) {
alert("failed");
}
});
}
The aspx.cs page (Code Behind page):
[WebMethod]
public static void Save()
{
// throw new DivideByZeroException(); // USED THIS TO VERIFY IF WEBMETHOD IS HIT.
_default obj = new _default();
obj.Show("Save Method Works"); // THIS IS A POPUP MESSAGE BOX
obj.btnSave_Click(); // THIS IS THE SAVE METHOD ON THIS PAGE THAT WE WANT TO RUN
}
public void btnSave_Click()
{
// METHODS CODE HERE
}
The ValidateForm function responds with "success", however, it doesn't seem like it is even triggering the WebMethod on the Code Behind page. If I use the I.E. Console Network tab, I can see the POST request. However, on the code behind method, it never triggers the breakpoints in debug (Not sure if it should according to some posts). At one point I inserted line to throw a DivideByZero exception and it never raised the exception.
So, to summarize, I get confirmation that he Javascript call to the WEBMETHOD worked by virtue of the success message and the POST message in the F12 Console Network tab. However, it doesn't seem that the WEBMETHOD ever fires. Any help would be appreciated !
You could try this to test an error instead of throwing an exception
Response.Clear();
Response.StatusCode = 500;
Response.End;
Not sure what I did, but I think adding "UseHttpGet = false" allowed it to finally execute the webmethod.
[WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = false)]
public static void Save()
{
// throw new DivideByZeroException(); // USED THIS TO VERIFY IF WEBMETHOD IS HIT.
_default obj = new _default(); // SINCE THIS METHOD IS STATIC, WE HAVE TO INSTANTIATE AND INSTANCE OF THE DEFAULT PAGE CLASS TO ACCESS METHODS ON THIS PAGE
obj.Show("Save Method Works"); // THIS IS A POPUP MESSAGE BOX
obj.btnSave_Click(); // THIS IS THE SAVE METHOD ON THIS PAGE THAT WE WANT TO RUN
}
function ValidateForm() {
var text = "This is a Test";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf=8",
data: "{}",
url: "default.aspx/Save",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert("status: " + textStatus);
alert("Error: " + XMLHttpRequest.responseText);
}
});
}

How to call a non-static method from aspx

I've a Method in the code behind of my aspx page, I need to call Two methods from Javascript, the problem that I'm Having is that I was trying to do it with a Json request and a WebMethod, but this method has to be static and the page components and other methods cannot be accessed from this method.
I was trying something Like:
javascript Function
function Func(Value) {
var conf=confirm('Sure? '+valor)
if (conf==true)
{
BlockAction();
}
}
function BlockAction() {
$.ajax({
type: "POST",
url: 'frmVentaTelefonica.aspx/BlockAction',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
})};
Code-behind code:
[WebMethod]
public static void BlockAcction()
{
try
{
frmVentaTelefonica venta = new frmVentaTelefonica();
venta.ConsultarVentaTelefonica();
venta.ImprimirTiquetes();
}
catch (Exception e)
{
throw;
}
}
I want to call those two methods when the confirm is true.
Update:
In need to accesses to two methods like this:
public void ConsultarVentaTelefonica()
{
DatosImpresion = new List<Impresion>();
IServicioVentas servicioVentas;
servicioVentas = SATWebServiceLocator<IServicioVentas>.ObtenerServicio();
string Tiquetes = string.Empty;
foreach (GridDataItem dataItem in gridInfoVentaTelefonica.MasterTableView.Items)
{
if ((dataItem.FindControl("CheckBox1") as CheckBox).Checked)
{
Tiquetes = Tiquetes + (dataItem["Tiquete"]).Text + ",";
}
}
Tiquetes = Tiquetes.TrimEnd(Tiquetes[Tiquetes.Length - 1]);
Tiquetes = " " + Tiquetes + " ";
DataSet dsResultado = servicioVentas.EntregaTelefonica(sessionR8A.Turno.IdTurno, Tiquetes);
if (dsResultado.Tables.Count > 0 && dsResultado.Tables[0].Rows.Count > 0)
Just run it when is true, those methods update in the database and print a ticket(first reading a grid checked items)
If you are trying to update the UI controls, or read their values, then what you are describing is the UpdatePanel control. A page webmethod cannot update any control and refresh the UI (unless through JavaScript). If you want to update the state of the page async, UpdatePanel is what you are looking for.
If you are trying javascript just because you dont want to refresh the page, then go for Update Panel . The answer for your question is 'No' you cant access non-static methods like how you want to do.
The reason it supports only static methods is that page instantiation is not done, if you want to use non static web methods then go for web service(.asmx).

ajax script alert jquery

I create static web method and then i try to call this into script like this
UPDATE SCRIPT
<script type="text/javascript">
debugger;
alert("1");
$(function () {
$.ajax({
type: "GET",
url: "Maintenance.aspx/data_call",
//data: "",
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert("12");
debugger;
var re = JSON.parse(result.d).response;
debugger;
console.log(JSON.parse(result.d).response);
debugger;
},
error: function (error) {
alert(Error);
}
});
});
</script>
UPDATE
code
[WebMethod]
public static string data_call()
{
string result="";
Data td=new Data();
List<spselect_data_Result> selectdata=td.spselect_data().ToList();
DataTable dt=new DataTable();
dt.Columns.Add("RegionID",typeof(int));
dt.Columns.Add("Region",typeof(string));
dt.Columns.Add("StartDate",typeof(DateTime));
dt.Columns.Add("EndDate",typeof(DateTime));
foreach(var add in selectdata)
{
dt.Rows.Add(add.RegionID,add.Region,add.StartDate,add.EndDate);
}
result=DataSetToJSON(dt);
return result;
}
public static string DataSetToJSON(DataTable dt)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
object[] arr = new object[dt.Rows.Count + 1];
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
arr[i] = dt.Rows[i].ItemArray;
}
// dict.Add(dt.TableName, arr);
dict.Add("response", arr);
JavaScriptSerializer json = new JavaScriptSerializer();
return json.Serialize(dict);
}
protected void Page_Load(object sender, EventArgs e)
{
// data();
}
when i debug code then an alert show like this
function Error (){[native code]}
and when when i set debugger on jquery and check then debugger comes on alert 1 and then on this line $(function() { then after this directly execute on this line means ajax not call
first i try to display data on console
error on console
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
When I try this the call only shows alert("1"). alert("12") is not called. Where is the problem?
This problem maybe caused by maxJsonLength property in web.config file. To solve the problem You can chnage the MaxJsonLength property on your web.config:
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
</configuration>
The MaxJsonLength property is an integer property that by default set to 102400(100k) and cannot be unlimited.
I see some problems in the code you posted.
First of all you don't need type: "POST" as you are not posting/sending any data.
So update that portion in ajax request.
$(function() {
$.ajax({
type: "GET",
url: "Maintenance.aspx/YourMethod",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
alert("12");
debugger;
},
error: function (error) {
alert(Error);
}
});
});
Or else to work it with post you will have to set
data: "{}",
See instead of setting cache:false in ajax request set it from a common place like
$(document).ready(function() {
$.ajaxSetup({ cache: false });
});
Next on server side no need to call the method data in page load.
Just write it directly in class outside page load.And add the attribute WebMethod from System.web.services.
[WebMethod]
public static string YourMethod()
{
return "whatever you want";
}
Note : Also another thing I noticed that you made your method name as data,so my advice is change it to something meaningful as data is a ajax call parameter key and it could conflict.

How to send data from JQuery Ajax to ASP.NET page?

I'm using JQuery Ajax to send a data from one domain to an ASP.NET page that is in another domain. I'm able to get the response back from ASP.NET page but I'm not able to send the data from JQuery Ajax. Here is my code:
$.ajax({
url: 'http://somewebsite/dbd/leap.aspx',
data: '{ year: "' + $('#txtYear').val() + '"}',
type: 'POST',
async: true,
cache: false,
dataType: 'jsonp',
crossDomain: true,
contentType:"application/json; charset=utf-8",
success: function (result) {
console.log("inside sucess");
console.log("result: " + result);
},
error: function (request, error) {
// This callback function will trigger on unsuccessful action
alert('Error!');
}
});
I can reach leap.aspx page. Note http://somewebsite is just a placeholder.
leap.aspx has the following:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="leap.aspx.cs" Inherits="_Default" %>
<%=output %>
leap.aspx.cs has the following: Note I'm using Request.Params["year"] to get the value of year passed by Ajax call but no luck.
using System;
public partial class _Default : System.Web.UI.Page
{
public string output = "";
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Params["callback"] != null)
{
output = Request.Params["callback"] + "('" + GetData(Request.Params["year"]) + "')";
}
}
[System.Web.Services.WebMethod]
public string GetData(string year)
{
return "From outer space! " + year;
}
}
When I run this code, in console I see
"result: From outer space!"
but I do not see the data sent for year by Ajax. I'm using JSONP because I'm making a cross-domain request to get around Same Origin Policy. I'm not getting any error. I'm just not getting the getting the value of year returned from ASP.NET page.
How do I get the year?
Change the data setting to remove the quotes like this:
data: { year: $('#txtYear').val() },
Had the same issue with a pre-defined object and this helped me.

onserverclick event not working using html builder in C#

I am using anchor tag and I want to fire event on click anchor tag.But unfortunately it is not working . Here is my code :
html.Append("<a id='dltTag' class='ca_quy_e' runat='server' onserverclick='Delete_Click'>");
html.Append("<i class='fa'>");
html.Append("</i>");
html.Append("</a>");
protected void Delete_Click(object sender, EventArgs e)
{
//My code
}
Every thing working perfect like table is forming , but only onserverclick not working.
You have to make use of javascript or jQuery i.e. clientside scripting for calling serverside method from client side
a. create method with wemethod attribute
[WebMethod]
public static string IsExists(string value)
{
//code to check uniqe value call to database to check this
return "True";
}
b. register client call with element
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
txtData.Attributes.Add("onblur", "focuslost()");
}
c. make use of jquery Ajax
function IsExists(pagePath, dataString, textboxid, errorlableid) {
$.ajax({
type:"POST",
url: pagePath,
data: dataString,
contentType:"application/json; charset=utf-8",
dataType:"json",
error:
function(XMLHttpRequest, textStatus, errorThrown) {
$(errorlableid).show();
$(errorlableid).html("Error");
},
success:
function(result) {
var flg = true;
if (result != null) {
flg = result.d;
if (flg == "True") {
$(errorlableid).show();
}
else {
$(errorlableid).hide();
}
}
}
});
}
function focuslost() {
var pagePath = window.location.pathname + "/IsExists";
var dataString = "{ 'value':'" + $("#<%= txtData.ClientID%>").val() + "' }";
var textboxid = "#<%= txtData.ClientID%>";
var errorlableid = "#<%= lblError.ClientID%>";
IsExists(pagePath, dataString, textboxid, errorlableid);
}
if you are not getting than here is full article : Calling Server Side function from Client Side Script
if you are using scriptmanager than you can use this Execute server side code from JavaScript using Script Manager
you need to use _dopostBack for psotbacking to server or make use of ajax to call server side method
Read:
Usage of doPostBack in a Real Environment
Example
html.Append("<a id='dltTag' class='ca_quy_e' runat='server' onclick='DoPostBack()'>");
html.Append("<i class='fa'>");
html.Append("</i>");
html.Append("</a>");
function DoPostBack()
{
__doPostBack('DeleteButton','');
}

Categories

Resources