Call cs function with data in js using ajax - c#

I want to access cs function from js function in aspx page after the user click on Delete button. and send id to the cs function.
I try the below codes:
js
function deleteClick(ID) {
'<%Session["ID"] = "' + ID + '"; %>';
var x = '<%= Session["ID"] %>';
alert(x);
$.ajax({
type: "POST",
url: "AddPI.aspx/deleteClick",
//data: ' {ID:"' + ID + '"}',
data: JSON.stringify({ ID: "' + ID + '" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Success");
},
failure: function (response) {
alert("Error");
}
});
}
cs
public void deleteClick(String ID)
{
Session["ID"] = Request.Params["ID"];
var id = "";
id = Session["ID"].ToString();
DialogResult myResult;
myResult = MessageBox.Show("Are you sure?", "Delete Confirmation",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (myResult == DialogResult.OK)
{
errorbox.Visible = false;
//connect to database and delete
}
}
the problem is the id can't be passed!
EDIT:
i solve the problem by change the cs function to static and edit the below field:
data: "{ ID: '" + ID + "'}",
that's it.
Now the problem is how to change the visibility of aspx div in a static cs function?
errorbox.Visible = false;
i got: Ann object reference is required for the non-static field....
i try call js on success
success: setVisibility,
and in the js:
$("#errorbox").hide();
but it does not works!

//Js Code
function deleteClick(ID) {
alert(ID);
$.ajax({
type: "POST",
url: "Default.aspx/deleteClick",
data: '{ID: "'+ID+'" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
failure: function (response,a,a2) {
alert("Not Done");
}
});
}
//c# Code
[System.Web.Services.WebMethod]
public static string deleteClick(string ID)
{
//Your Code
return null;
}

Noting your first issue is solved by you which is awesome! :)
and you have another problem in which you need to change the visibility of a div on error occurrence. Well you change the visibility of div errorbox to true as default value
errorbox.Visible = true;
and on your script section, hide this div using jquery:
$(function(){
$('[id$=errorbox]').hide(); //this will auto-run after page is completely loaded.
});
make little changes to your cs function such as:
public string deleteClick(String ID)
{
Session["ID"] = Request.Params["ID"];
var id = "";
id = Session["ID"].ToString();
DialogResult myResult;
myResult = MessageBox.Show("Are you sure?", "Delete Confirmation",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (myResult == DialogResult.OK)
{
errorbox.Visible = false;
//connect to database and delete
return "true"; //if successful
}
return "false"; //if not successful
}
and then if any error occurs on your ajax response(success/error) simply just do this in your ajax:
success: function (response) {
if(response.d == "true")
{
alert('success');
}
else{
$('[id$=errorbox]').show();
}
},
error: function (response) {
$('[id$=errorbox]').show();
}

Related

Awake Devexpress component by Ajax

I use devextreme for asp.net web forms. I catch my mahID by debug on my metod. I wanna do postback on serverside like refresh i donno.
I can tell what happening on my server side the all components dont load what i have on aspx design side. How can i awake my labels,charts etc.
THANKS.
C# Server Side
public void MahalleBilgileriGetir(int mahalleId)
{
View_MuhtarBursaMahalle mahalle = View_MuhtarBursaMahalle.BursaMahalleGetir(mahalleId);
if (mahalle != null)
{
lblMuhtarlikAdi.Text = string.Format("{0} - {1}", mahalle.MahalleAdi, mahalle.IlceAdi);
lblMuhtar.Text = string.Format("{0}", mahalle.AdSoyad);
lblCepTelefon.Text = string.Format("{0}", mahalle.Telefon);
lblDonemi.Text = string.Format("{0}", mahalle.Donemi);
flMuhtar.Visible = true;
ChartNufus.DataSource = chartNufusBul(mahalle.MahalleAdi, mahalle.ErkekNufusu, mahalle.KadinNufusu, mahalle.ToplamNufusu);
ChartNufus.DataBind();
ChartTitle chartTitle = new ChartTitle() { Text = string.Format("{0} Toplam Nüfusu: {1}", mahalle.MahalleAdi, mahalle.ToplamNufusu.HasValue ? mahalle.ToplamNufusu.Value : 0) };
ChartNufus.Titles.Clear();
ChartNufus.Titles.Add(chartTitle);
ChartNufus.Visible = true;
SecimBilgileriGetir(mahalleId, mahalle.MahalleAdi);
VergiGelirleriGetir(mahalleId, mahalle.MahalleAdi, mahalle.ToplamNufusu);
chartSecim2014.Visible = true;
chartSecim2018.Visible = true;
chartSecim2019.Visible = true;
}}
JS
if (mah_adi !== undefined) {
$.ajax({
type: "POST",
url: "MahalleBilgileri.aspx/MahalleBilgileriGetir",
data: '{mahID: "' + e.target.attribute("mahid") + '" }',
async: false,
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response) {
console.log("ajax", response);
}
}
});
}

Send data from layout to controller Asp.Net MVC

I have a switch button on my navbar on my layout view, when I click the button It changes the value and send it to the controller:
<input type="button" id="switchbutton" value="Weekend" style="color:blue" onclick="toggle(this)" >
<script type="text/javascript">
function toggle(button) {
switch (button.value) {
case "Weekend":
button.value = "Week";
break;
case "Week":
button.value = "Weekend";
break;
}
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{param: "' + $(this).val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("Return Value: " + response);
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
}
</script>
On the controller I receive the value and send it to an If statement that executes a function depending on the value received.
private string SwitchVal;
[HttpPost]
public string AjaxMethod(string param)
{
var d = string.Empty;
switch (param)
{
case "Weekend":
d = "Week";
break;
case "Week":
d = "Weekend";
break;
}
SwitchVal = d;
return d;
}
public JsonResult ModelsUpdate(string SwitchVal)
{
if (SwitchVal == "Weekend")
{
resultminDate = CalculateminDate(minDate, todayDay);
}
else
{
resultminDate = CalculateminDateWeek(minDate, todayDay);
}
The problem is that I do click on the button and I don't see any change, It seems that the value only arrives to the controller the first time. Can anybody help me on this?
It doesn't work like that. You can't hold the values in server side for multiple different requests. Maybe you can use Session to perform it but why don't you post the data ModelsUpdate action instead of AjaxMethod. In your case, I couldn't understand the purpose of AjaxMethod.
public JsonResult ModelsUpdate(string SwitchVal)
{
if (SwitchVal == "Weekend")
{
resultminDate = CalculateminDate(minDate, todayDay);
}
else
{
resultminDate = CalculateminDateWeek(minDate, todayDay);
}
return Json(resultminDate);
}
Ajax call looks like
$.ajax({
type: "POST",
url: "/Home/ModelsUpdate",
data: '{SwitchVal: "' + $(this).val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("Return Value: " + response);
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});

Jquery UI Modal Dialog Not Working Properly

I created a jQuery modal password dialog box to redirect to a page for password validation.
The modal dialog appears alright, but instead of executing the method that handles the password validation it instead shows the error [object Object] on a the browsers alert dialog. I'm trying to figure out what I'm doing wrong here.
Below is my code:
JavaScript/jQuery
$(document).on("click", "[id*=lnkView1]", function() {
$("#dlgPassword").dialog({
title: "View Details",
buttons: {
Go: function() {
var valPassword = $("[id*=cpgnPassword]").val();
var hdfCamId = $('#<%=rptCampaigns.ClientID %>').find('input:hidden[id$="hdfCampaignID"]').val();
$("[id*=hdfCampaignID2]").val(hdfCamId);
//var jsonObj = '{password: "' + valPassword + '"}';
var res;
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{password: "' + valPassword + '"}',
dataType: 'json',
url: 'CampaignsList.aspx/ValidatePasswordWM',
success: function(data) {
alert('successful')
},
error: function(err) {
alert(err.toString());
}
});
$(this).dialog('close');
}
},
modal: true
});
return false;
});
Code-Behind
protected void ValidatePassword(object password)
{
var campaign = new CampaignsService().GetByCampaignId(hdfCampaignID2.Value);
if (campaign != null)
{
if (campaign.Password.Equals(password))
Response.Redirect("CampaignDetails.aspx?CampaignID=" + hdfCampaignID2.Value);
}
}
[WebMethod]
public static void ValidatePasswordWM(object password)
{
CampaignsList page = new CampaignsList();
page.ValidatePassword(password);
}
Can someone help me figure out what's wrong?
You need the appendTo property on your dialog so it gets added to the form properly.
$("#dlgPassword").dialog({
title: "View Details",
appendTo: "form",
buttons: {
...
Instead of err.toString(), try err.message
This code shows a products cadastre at jQuery UI. When OK button pressed, re-populate dropdownlist.
Javascript:
$dialog = $("#dlgCadastroProduto").dialog({
modal: true,
autoOpen: false,
height: 500,
width: 700,
buttons: {
Ok: function () {
$(this).dialog("close");
$("#lstProducts").empty();
$("#lstSelectedProducts").empty();
$.ajax({
type: "GET",
url: '/Produto/jsonLoad',
async: true,
dataType: 'json',
success:
function (data) {
//alert('sucesso');
$.each(data, function (index, value) {
//insere elemento na droplist
$("#lstProducts").append('<option value='+value.ID+'>'+value.Descricao+'</option>')
});
},
error: function (data) {
//alert(data);
}
});
}
}
});
$("#btnCadastroProduto").button().on("click", function () {
$dialog.dialog("open");
});
Code-Behind at Controller:
public JsonResult jsonLoad()
{
var lista = _produtoBLL.FindAll();
var xpto = lista.Select(x => new { Id = x.ID, Descricao = x.Descricao });
return Json(xpto, JsonRequestBehavior.AllowGet);
}
I hope i have helped
This is just sample code you can you with yours
Client Side
var mparam = "{param1:'" + mvar1 + "',param_n:'" + mvar_n + "'}";
$.ajax({
type: "POST",
url: "file_name.aspx/web_method",
data: mparam,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Response) {
try {
var msdata = JSON.parse(Response.d);
if (msdata.err == "0") {
location.replace("newlocation");
}else{
alert("Error:" + msdata.msg);
}
} catch (e) {
alert("Error in JSON parser error:" + e.description);
}
},
error: function (medata) {
alert("Internal Server Error:" + medata);
}
});
Server Side
[System.Web.Services.WebMethod]
public static string web_method(string param1, string param_n)
{
string strerror = "0", strmessage = "";
try
{
strerror = "0";
}
catch (Exception ex)
{
strerror = "2";
strmessage = ex.Message;
}
return "{\"err\":\"" + strerror + "\",\"msg\":\"" + strmessage + "\"}";
}

How to use ajax to call a boolean web method

I want to use an ajax call to check if Boolean is true or false.
here is my web method:
[WebMethod]
public Boolean Login(string uname, string password)
{
if (ValidateUser(uname, password))
{
FormsAuthentication.Authenticate(uname, password);
return true;
}
return false;
}
and here is my ajax call but its not working
$(document).ready(function () {
$('#btnLogin').click(function () {
var username = "test"
var password = "1234"
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "wsLogin.asmx/Login",
data: "{uname: '" + username + "'" + ",pwd: '" + password + "' }",
dataType: "Json",
success: function (success) {
alert("Boolean True");
},
error: function (error) {
alert("Boolean False");
}
});
});
});
I am trying to create a login so I am using a Boolean to check if the user is authenticated
Unfortunately ajax seems to .toString() the answer so what was a boolean becomes a "True" or "False" if you return a Json data structure instead like
return Json(new { Error = true, ErrorMessages = new []{e.Message} });
the values will be truly boolean.
I had the same problem.
I realised that the error: function (error) {} never gets called, even when my webmethod returned false.
What's actually happening is that as long as the webmethod does not produce any errors itself (like exceptions), then the error function will never fire! The webmethod will always be a 'success'!
So place your true/false logic inside the success function:
$(document).ready(function () {
$('#btnLogin').click(function () {
var username = "test"
var password = "1234"
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "wsLogin.asmx/Login",
data: "{uname: '" + username + "'" + ",pwd: '" + password + "' }",
dataType: "Json",
success: function (result) {
if(result == "true")
alert("Boolean True");
else
alert("Boolean False");
},
error: function (error) {
error = error; //do nothing
}
});
});
});
try this:
$(document).ready(function () {
$('#btnLogin').click(function () {
var username = "test"
var password = "1234"
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "wsLogin.asmx/Login",
data: "{uname: '" + username + "'" + ",pwd: '" + password + "' }",
dataType: "Json",
success: function (data) {
if(data)
alert("Boolean True");
else
alert("Boolean False");
},
error: function (error) {
alert("Error");
}
});
});
});

jQuery autocomplete shows undefined values while WebService is returning correct data

$(function() {
$(".tb").autocomplete({
source: function(request, response) {
$.ajax({
url: "MyService.asmx/GetCompletionList",
data: "{ 'prefixText': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item.Email
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1
});
});
This is my jQuery code and WebService method. Can any one help me?. GetCompletionList WebService method returns list of string but autocomplete on TextBox shows undefined for all values
public List<string> GetCompletionList(string prefixText)
{
RegistrationBAL _rbal = new RegistrationBAL(SessionContext.SystemUser);
DataSet ds = new DataSet();
_rbal.LoadByContextSearch(ds, prefixText);
List<string> myList = new List<string>();
foreach (DataRow row in ds.Tables[0].Rows)
{
myList.Add((string)row[0]);
}
return myList.ToList();
}
Try to change the data in the ajax call as follows
if the auto complete is done for an asp control
data: "{'prefixText':'" + document.getElementById("<%= ContactName.ClientID %>").value + "'}",
or else give as follows
data: "{'prefixText':'" + document.getElementById("requiredID").value + "'}",
edited answer where the auto complete works
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AutoCompleteService.asmx/GetAutoCompleteData",
data: "{'PhoneContactName':'" + document.getElementById("<%= ContactName.ClientID %>").value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
//alert("Error");
}
});
}
});
}
which resembles your ajax function but in server side I used the web service as below which the get values from the database
public class AutoCompleteService : System.Web.Services.WebService
{
[WebMethod]
public List<string> GetAutoCompleteData(string PhoneContactName)
{
List<string> result = new List<string>();
string QueryString;
QueryString = System.Configuration.ConfigurationManager.ConnectionStrings["Admin_raghuConnectionString1"].ToString();
using (SqlConnection obj_SqlConnection = new SqlConnection(QueryString))
{
using (SqlCommand obj_Sqlcommand = new SqlCommand("select DISTINCT PhoneContactName from PhoneContacts where PhoneContactName LIKE +#SearchText+'%'", obj_SqlConnection))
{
obj_SqlConnection.Open();
obj_Sqlcommand.Parameters.AddWithValue("#SearchText", PhoneContactName);
SqlDataReader obj_result = obj_Sqlcommand.ExecuteReader();
while (obj_result.Read())
{
result.Add(obj_result["PhoneContactName"].ToString().TrimEnd());
}
return result;
}
}
}
}
.. Hope this helps :D

Categories