ASP.NET ajax call using Jquery adds to list - javascript

I have a simple UI where I am trying to populate the select dropdown using data from database. I am doing this by a AJAX call to fetch the data.
The C# web method looks like
private static List<List<string>> componentTypeDropDown = new List<List<String>>();
private void loadDropDownList()
{
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand("SELECT FieldName,FieldLabel FROM dropDownFields", conn);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
List<String> temp = new List<string>();
temp.Add((string)dr.GetValue(0));
temp.Add((string)dr.GetValue(1));
componentTypeDropDown.Add(temp);
conn.Close();
}
}
[WebMethod]
public static ArrayList getComponentType()
{
ArrayList compType = new ArrayList();
for (int i=0;i<componentTypeDropDown.Count();i++)
{
compType.Add(new { label = componentTypeDropDown[i][0], value = componentTypeDropDown[i][1] });
}
return compType;
}
The AJAX call looks like
$.ajax({
type: "POST",
url: "salesQuote.aspx/getComponentType",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log("karan");
},
error: function () {
alert("Failed to load names");
}
});
Every time I refresh or even restart the server the value of msg in success callback has previous values as well. For example lets say my database has value 1,2. First time I call ajax msg is 1,2 if i refresh the value is 1,2,1,2 and so on. Even if I close the server and start again the value would be 1,2,1,2,1,2

Your ComponentTypeDropdown is a static, so every time you call 'LoadDropdownList' this list will add new items, whitout removing the old ones.
I would suggest that you add following line in the loadDropDownList method:
private void loadDropDownList()
{
componentTypeDropdown.RemoveAll();
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand("SELECT FieldName,FieldLabel FROM dropDownFields", conn);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
List<String> temp = new List<string>();
temp.Add((string)dr.GetValue(0));
temp.Add((string)dr.GetValue(1));
componentTypeDropDown.Add(temp);
conn.Close();
}
}

Related

Authorization issues with Ajax

I ran into a problem with Ajax: i am calling a server side function via Ajax. Nothing strange so far. The problem is that it doesn't give me back any results and while debugging, I found that it gives permission problems. I don't understand where the problem is.
CODICE AJAX
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
let parametri = { utente: user, Password: pass }
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebControls.aspx/CliccaBottone",
data: JSON.stringify(parametri),
dataType: "json",
success: function (i) {
if (i == 0) {
alert("Le credenziali sono errate");
}
else {
alert("Hai eseguito il login");
}
}
});
CODICE C#
public partial class WebControls : System.Web.UI.Page
{
[WebMethod(EnableSession = true)]
public static int CliccaBottone(string utente, string Password)
{
string queryString = "SELECT * FROM Credenziali WHERE Username = #User AND Pass = #Password";
int i = 0;
//VIENE APERTA LA CONNESSIONE COL DB
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["coso"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(queryString, connection))
{
SqlParameter parameter = new SqlParameter("User", utente);
SqlParameter parameter2 = new SqlParameter("Password", Password);
command.Parameters.Add(parameter);
command.Parameters.Add(parameter2);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
i++;
}
reader.Close();
}
}
return i;
}
}
}
I suspect there is an error on the server side, because the syntax written on the client side seems correct to me. But logically if an incorrect function is called that will not work. Thank you very much for helping.
How are you handling credentials when connecting the the database itself? If it's pass through authentication, what credentials is your application using when accessing the database?

Ajax returning datatable always going in error part in asp.net

I return list of values in a datatable and that I want to fill in success part of ajax function in dropdownlist. Till return dt I get all the values properly but after that it goes in error part. Below is what I tried.
Ajax function
function getMZONEWithState(evt) {
var ddlState = $('#ContentPlaceHolder1_ddlState').val();
var ddlMaintenanceZone = $("#ddlMaintenanceZone");
ddlMaintenanceZone.empty().append('<option selected="selected" value="0" disabled = "disabled">State Loading...</option>');
$.ajax({
type: "POST",
url: "Dashboard.aspx/GetMaintZone",
data: JSON.stringify({ ddlState: ddlState }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function (response) {
alert('Something went wrong..!!');
}
});
}
And in code behind:-
[WebMethod]
public static DataTable GetMaintZone(string ddlState)
{
DataTable dt = new DataTable();
try
{
CommonDB ObjCommon = new CommonDB();
dt = ObjCommon.GetMZONE(ddlState);
return dt;
}
catch (Exception)
{
throw;
}
}
Why it always goes in error part I don't understand ?? Please suggest If I am going wrong anywhere.
You can't return DataTable directly from your [WebMethod] like this. You need to convert your DataTable to JSON before sending to cleint.
Change your server side code like following.
[WebMethod]
public static string GetMaintZone(string ddlState)
{
DataTable dt = new DataTable();
try
{
CommonDB ObjCommon = new CommonDB();
dt = ObjCommon.GetMZONE(ddlState);
return DataTableToJSON(dt);
}
catch (Exception)
{
throw;
}
}
public static string DataTableToJSON(DataTable table)
{
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
Dictionary<string, object> childRow;
foreach (DataRow row in table.Rows)
{
childRow = new Dictionary<string, object>();
foreach (DataColumn col in table.Columns)
{
childRow.Add(col.ColumnName, row[col]);
}
parentRow.Add(childRow);
}
return jsSerializer.Serialize(parentRow);
}
}

Why is my C# method not being called from AJAX?

I am trying to call the following C# method:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string getJSONdata()
{
string jsonString = "";
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM DRAW ORDER BY DrawID DESC;", con))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
List<Dot> _Dot = new List<Dot>();
while (reader.Read())
{
Dot dot = new Dot();
dot.x = (int.Parse(reader["xCoord"].ToString()));
dot.y = (int.Parse(reader["yCoord"].ToString()));
if (reader["DrawID"] != DBNull.Value)
dot.i = (int.Parse(reader["DrawID"].ToString()));
_Dot.Add(dot);
}
JavaScriptSerializer jss = new JavaScriptSerializer();
jsonString = jss.Serialize(_Dot);
}
}
}
System.Diagnostics.Debug.WriteLine(" JSON: " + jsonString);
return jsonString;
}
Here is my JavaScript code:
$.ajax({
url: 'Default.aspx/getJSONdata',
data: '{ }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
alert(response.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
First, I am getting the ajax error. No idea why it's not called.
Second, I am still not sure I am returning the correct JSON data I want, whether in the correct format or not. Thanks for your help.
Edit. It is returning a JSON string correctly.
Note: the connectionString works in another function, so that's not it.
Download and install Fidder4.
This will allow you to see the traffic between your page and your server. You can see the actual call URL and then paste it into a browser to see what it returns. This will give you a tool to solve this type of problem going forward.

How to pass value from client side to server side in asp.net?

how to pass the value in below script to the server side
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function(response) {
if (response.authResponse) {
FB.api('/me', function(me) {
document.getElementById('auth-displayname').innerHTML = me.name;
document.getElementById('Email').innerHTML = me.email;
document.getElementById('gender').innerHTML = me.gender;
document.getElementById('birth').innerHTML = me.birthday;
document.getElementById('firstname').innerHTML = me.first_name;
})
Javascript variables exist on the client so in order to get those values into the server you'll need to execute a request from the client.You probably want an approach called AJAX. AJAX involves Javascript making requests to the server in the background of your page. You'll set up a C# web page that expects these background requests. If you use a GET request then then place the variables in the query string of your AJAX request to your new C# page. If you want to use a POST request then you'll set parameters in the data that you post to your page.
Libraries like jQuery make this kind of thing pretty simple.
In webform2.aspx
<script type="text/javascript">
function LoadValues(me) {
{
var Email = me.email;
var Name = me.name;
var Id = me.id;
var Dob = me.birthday;
var Gender = me.gender;
alert(Email)
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
var data2Send = '{"fbemail": '+Email+', "fbname":'+Name+', "fbid":'+Id+',"fbname":'+Dob+',"fbname":'+Name+' }';
$.ajax({
type: "POST",
url: 'webform2.aspx/Testmethod',
data: data2Send,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (arg) {console.log(arg) //call successfull
$("#lbltxt").text(arg);
},
error: function (xhr) {
alert(xhr); //error occurred
}
});
}
</script>
In webform2.aspx.cs
[System.Web.Services.WebMethod]
public static string TestMethod(string fbid, string fbemail, string fbsex, string fbdob)
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataReader datareader;
con = new SqlConnection(".......");
cmd = new SqlCommand("SpFacebookInfo", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FbId", fbid);
cmd.Parameters.AddWithValue("#FbEmail", fbemail);
cmd.Parameters.AddWithValue("#FbSex", fbsex);
cmd.Parameters.AddWithValue("#FbDob", fbdob);
datareader = cmd.ExecuteReader();
datareader.Close();
return fbemail;
}
}
Set the value in a hidden variable as u did and do a document.myform.submit();
to go to Page_Load and read the variables

MVC 3 .NET Fill fields dynamically

I have a field for a ZIP Code.
I want that, when the person fills this field with a zip code and click in another field, triggers a event (onBlur).
This Event will execute a select in database and get the address and fill the other fields with this information.
I read that is not a good idea execute a Controller Method from the View.
So, how can I develop this?
My zip code field:
<div class="editor-field">
#Html.Label("ZIP CODE")
#Html.Editor("zipCodeClient")
</div>
Thanks!
If you have access to jQuery I would use it's ajax function to call a wcf web service that returns the relevant address information in a JSON format. Otherwise, you could create your own XHR request and parse the response.
$('#zipCodeClient').blur(function() {
var zipCode = $(this).val();
if(zipCode.length >= 5 && zipCode.length <= 10) {
$.ajax({
type: 'GET',
data: { ZipCode: zipCode },
url: 'something/ZipCodeToAddressService',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data) {
var responseObject = jQuery.parseJSON(data);
$('#cityTextBox').val(responseObject.City);
$('#stateTextBox').val(responseObject.State);
}
});
}
else {
// zip code not valid
}
});
In WCF:
[ServiceContract()]
public interface IAddressServices
{
[OperationContract()]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
string ZipCodeToAddressService(string ZipCode);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class AddressServices : IAddressServices
{
public string ZipCodeToAddressService(string ZipCode)
{
using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
{
using (SqlCommand sqlCmd = new SqlCommand("ZipCodeToAddressStoredProc", sqlConnection))
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add("#Zip", SqlDbType.NVarChar).Value = ZipCode;
sqlConnection.Open();
SqlDataReader sDR = sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable tbl = new DataTable();
tbl.Load(sDR);
sDR.Close();
var citystateData = from DataRow Row in tbl.AsEnumerable()
select new
{
City = Row.Field<string>("City"),
State = Row.Field<string>("State")
};
JavaScriptSerializer js = new JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
js.Serialize(cityStateData, sb);
string rtrnCityStateData = sb.ToString();
return rtrnCityStateData;
}
}
}
}

Categories

Resources