onserverclick event not working using html builder in C# - javascript

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','');
}

Related

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

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.

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.

How to pass a string from javascript to server? and then get a return value from server in asp.net webforms

I have this modal. inside a form tag
<div id="Incoming_Call" class="modal fade" role="document">
<asp:Label runat="server" id="Caller_id" Text="Incoming Call"</asp:Label>
</div>
I want to change the label text when the modal will show
<script>
string id = "temporary value"//javascript has this value on clientside.
// i don't have this value on page load but after some event triggers.
$('#Incoming_call').on('shown', function(){
id="zetawars#hotmail.com";
var text = '<%= generatestring(id)%>';
$('#<%=Caller_id.ClientID%>').html = id;
});
</script>
I need to send that id variable to server side to a function generateString() after the string has changed from id="temporary Value" to id="zetwars#hotmail.com" or something
This is on server side.
public string generateString(string id)
{
id = // does some processing;
return id;
}
So, I want to send a variable of javascript to the server side then server has to do some processing and return the value. the javascript variable is not ready at page load time. So I can't pass it inside <%%> these tags and get a newer value. It will only pass "temporary value" as a string not the new value.
Calling a server side method from javascript is really simple.You can do this with jQuery $.ajax function and a [WebMethod]
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static string generateString(string id)
{
System.Diagnostics.Debugger.Break();
return String.Format("Response from server for - {0}.Call time - {1}",id,DateTime.Now.ToString("HH:mm:ss"));
}
.ASPX:
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var id = "temporary value";
$("#btnMakeAjaxCall").click(function () {
MakeAjaxCall();
});
function MakeAjaxCall() {
$.ajax({
type: "POST",
url: "AjaxCallExample.aspx/generateString",
contentType: "application/json;charset=utf-8",
data: '{id:"' + id + '"}',
dataType: "json",
success: function (data) {
var caller = '<%: Caller_id.ClientID %>';
$("#" + caller).text(data.d)
},
error: function (errordata) {
console.log(errordata);
}
});
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="button" id="btnMakeAjaxCall" value="Make AJAX call" />
<asp:Label ID="Caller_id" runat="server" Text="Incoming Call"></asp:Label>
</form>
</body>
You can make an ajax call to server and use the returned value.
you can make ajax call each time the modal is shown
or
you can make ajax call whenever you are ready to get result from server, this way you can make ajax call and store the result in a hidden variable on page or some other already defined variable and use the variable in modal.
jQuery code to make ajax call to server
To make ajax call you need to add reference to jQuery in your page.
$.ajax({
url: "/controller_name/method_name",
type: "POST",
data: { var1:var1},
success: function (response) {
//use response here
},
error: function () {
alert("Some unexpected error occured. Please try again.");
}
});
This is the way you can accomplish what you want, lets us know id you need help in coding also.

Categories

Resources