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);
}
}
});
}
Related
i have this jquery code, sending items to controller and download from controller, everything is fine
downloads is fine, i check response from in Chrome Network Tab is okay. but success function never run after process done. (i'm using async:false; already)
$(document).on('click', '#baslat', function (e) {
var token = $("#token").val();
var islemler = [];
var secililer = [];
$.each($("input[class='cc']:checked"), function () {
var islem = {};
islem.IslemTuru = $(this).attr("id");
islemler.push(islem);
});
$.each($("tr[class='sec']"), function () {
if ($(this).children('td:eq(1)').children("input[type='checkbox']").prop('checked')) {
var beyan = {};
beyan.Id = $(this).attr("id");
beyan.TahakkukId = $(this).data("id");
beyan.KisaKod = $(this).children('td:eq(2)').html();
beyan.BeyannameTuru = $(this).children('td:eq(4)').html();
beyan.Ay = $(this).children('td:eq(5)').html().substring(8, 10);
beyan.Yil = $(this).children('td:eq(5)').html().substring(11, 16);
secililer.push(beyan);
}
});
$.ajax({
url: '/Ebeyan/BeyanAl',
type: "POST",
dataType: "string",
async: false,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ secililer, islemler, token }),
success: function (data) {
$("#mesaj").html(data);
alert("done.");
}
});
});
The controller is here. I have to use Thread.Sleep (1000) in the method. because the server on which I want to download files wants 1 second to pass between each request.
public async Task<string> BeyanAl(List<Beyanname> secililer, List<Islem> islemler, string token)
{
bool indir = true;
bool yazdir = false;
bool gonder = false;
foreach (var islem in islemler)
{
if (islem.IslemTuru =="cbyazdir")
{
yazdir = true;
}
if (islem.IslemTuru == "cbgonder")
{
gonder= true;
}
}
foreach (var GelenBeyan in secililer)
{
string YolAdi = YolHazirla(GelenBeyan);
string DosyaAdi = DosyaAdiHazirla(GelenBeyan);
await dosyaindir(token, YolAdi + "/" + DosyaAdi, "Beyan", GelenBeyan.Id, "");
await dosyaindir(token, YolAdi + "/" + DosyaAdi, "Tahakkuk", GelenBeyan.Id, GelenBeyan.TahakkukId);
}
return "İndirildi";
}
here is chrome response screens
r1
r2
There is no 'string' data type in ajax datatypes make it json or text
$.ajax({
url: '/Ebeyan/BeyanAl',
type: "POST",
dataType: "string", <-- make it json or text
async: false,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ secililer, islemler, token }),
success: function (data) {
$("#mesaj").html(data);
alert("done.");
}
});
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();
}
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 + "\"}";
}
I want my function, which does an ajax call to controller, to return message from response.
I've tried this, but it doesnt work. How can acchieve my goal? is there a better solution for this?
var exists = personExists ();
if (exists != null) {
alert('The person already exists');
return;
}
var personExists = function () {
var exists = false;
var errorMsg = null;
$.ajax({
url: "#Url.Action("PersonExist", "Person")",
type: "POST",
dataType: 'json',
data: { name: self.name(), socialSecurityNumber: self.socialSecurityNumber() },
async: false,
contentType: "application/json",
success: function (response) {
if (response.exists) {
exists = true;
errorMsg = response.message;
}
}
});
if (exists)
return errorMsg;
return null;
};
You can do that with callback functions;
var personExists = function (callback) {
var exists = false;
var errorMsg = null;
$.ajax({
url: "#Url.Action("PersonExist", "Person")",
type: "POST",
dataType: 'json',
data: { name: self.name(), socialSecurityNumber: self.socialSecurityNumber() },
async: false,
contentType: "application/json",
success: function (response) {
if (response.exists) {
exists = true;
errorMsg = response.message;
callback(exists, errorMsg);
}
}
});
if (exists)
return errorMsg;
return null;
};
And usage;
personExists(function(exists, err) {
if (exists != null) {
alert('The person already exists');
return;
}
});
Simply, you can pass exists and errorMsg to callback. See here for further detail on callback functions
You need to use a callback:
function getErrorMessage(message) {
//do whatever
}
Inside the AJAX request:
$.ajax({
url: "#Url.Action("PersonExist", "Person")",
type: "POST",
dataType: 'json',
data: { name: self.name(), socialSecurityNumber: self.socialSecurityNumber() },
async: false,
contentType: "application/json",
success: function (response) {
if (response.exists) {
exists = true;
getErrorMessage(response.message); //callback
}
}
});
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");
}
});
});
});