Update dropdown list with ajax call in asp.net - c#

I have web page with dropdown list "ListBox" with email address of users.
How do I make a function that update the dropdownlist "ListBox" everytime when I add new email user in the dropdown list ?
I have trying this solution without success because the dropdown list it emptied, instead of add new user.
This is my code :
nnewuser.txuser = $("[id*=txuser]").val();
$.ajax({
type: "POST",
url: "prefix.aspx/Savepnusers" + qString,
data: '{nnewuser: ' + JSON.stringify(nnewuser) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if ($("[id*=txuser]").val()) {
alert("Ok");
alert(JSON.stringify(nnewuser));
$("[id*=ListBox1]").html(response);
}
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error : " + thrownError + JSON.stringify(nnewuser));
}
});
return false;
});
Savepnusers
public class pnnusers
{
public string txuser { get; set; }
}
[WebMethod(EnableSession = true)]
[ScriptMethod]
public static void Savepnusers(pnnusers nnewuser)
{
string sql = #String.Format(" INSERT INTO `tbl_email` (email) VALUES (?); ");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
using (OdbcCommand command =
new OdbcCommand(sql, cn))
{
try
{
command.Connection.Open();
command.Parameters.AddWithValue("param1", nnewuser.txuser.ToString());
command.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
command.Connection.Close();
}
}
}
}
DropDownList
private void MTListBox1()
{
DataTable dt = new DataTable();
sql = #String.Format(" SELECT ");
sql += String.Format(" LOWER(Email) AS UserEmail ");
sql += String.Format(" FROM ");
sql += String.Format(" tbl_email ORDER BY LOWER(Email) ASC; ");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
using (OdbcCommand command =
new OdbcCommand(sql, cn))
{
try
{
command.Connection.Open();
OdbcDataAdapter sqlDa = new OdbcDataAdapter(command);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
ListBox1.DataTextField = "UserEmail";
ListBox1.DataValueField = "UserEmail";
ListBox1.DataSource = dt;
ListBox1.DataBind();
}
}
catch (OdbcException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
command.Connection.Close();
}
}
}
}

There are 2 main problems here:
First, your Savepnusers method does not return anything, so you can't use response in AJAX calls. What you need is that re-initialize ListBox1 or append new item after Savepnusers complete successfully:
Secondly, it seems you can't send nnewuser as parameter correctly. You don't need to have pnnusers class instead just use string type as a parameter.
So server-side:
public static void Savepnusers(string nnewuser)
On client-side, you need to add dropdownlist item with jquery:
var txtUser = $("[id*=txuser]").val();
$.ajax({
type: "POST",
url: "prefix.aspx/Savepnusers",
data: JSON.stringify({ nnewuser: txtUser }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
//Since you can't use response object, you can append new item to dropdownlist
if (txtUser) {
$("[id*=ListBox1]").append('<option value="'+txtUser+'">'+txtUser+'</option>');
}
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error : " + thrownError + JSON.stringify(nnewuser));
}
});
See: asp dropdownlist dynamic value from javascript issue

Related

DropDownList bind from web service Not passing data source when Edit in asp.net

I am using web service to bind data in DropDownList when I Add New data drop down list working fine, but when I Edit mode drop data source not fill. so the question is how to fill data source when I am using web service to bind web service.
Html:
<asp:DropDownList ID="cmbFlightNo" class="form-control" runat="server" DataValueField="mFlightNo" DataTextField="mFlightNo" AppendDataBoundItems="true">
</asp:DropDownList>
webservies
[WebMethod]
public Airline_Flights[] Loadetails(string StuID)
{
string Conec = ConfigurationManager.ConnectionStrings["BriskCargo"].ConnectionString;
SqlConnection con = new SqlConnection(Conec);
con.Open();
SqlDataAdapter da = new SqlDataAdapter("Select FlightNo from AirLine_Flights where ALCode='" + StuID + "' and IsActive=1", con);
DataTable st = new DataTable();
da.Fill(st);
List<Airline_Flights> details = new List<Airline_Flights>();
foreach (DataRow dtrow in st.Rows)
{
Airline_Flights obj = new Airline_Flights();
obj.mFlightNo = dtrow["FlightNo"].ToString();
details.Add(obj);
}
JavaScriptSerializer ser = new JavaScriptSerializer();
return details.ToArray();
}
JQuery code to fill when change when fire.
function Load_Regno() {
var StuID = document.getElementById('ContentPlaceHolder1_cmbAirlines').value;
$.ajax(
{
type: "POST",
contentType: "application/json;charset=utf-8",
url: "AirlinesDropDown.asmx/Loadetails",
data: JSON.stringify({StuID: StuID }),
dataType: "json",
success: function (data) {
var theDropDown = document.getElementById("ContentPlaceHolder1_cmbFlightNo");
theDropDown.length = 0;
$.each(data.d, function (key, value) {
$("#ContentPlaceHolder1_cmbFlightNo").append($("<option></option>").val(value.mFlightNo).html(value.mFlightNo));
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.status == 0) {
alert(' Check Your Network.');
} else if (XMLHttpRequest.status == 404) {
alert('Requested URL not found.');
} else if (XMLHttpRequest.status == 500) {
alert('Internel Server Error.');
} else {
alert('Unknow Error.\n' + XMLHttpRequest.responseText);
}
}
});
return false;
}
[WebMethod]
public Airline_Flights[] Loadetails(string StuID)
{
var flightsList = GetFlightListByStuID(string StuID);
return selectedFlights.Select(x => x.FlightNo).ToArray();
}
// could be in another data access class etc.
private List<Airline_Flights> GetFlightListByStuID(string StuID)
{
List<Airline_Flights> selectedFlights = new List<Airline_Flights>();
string connectionString = ConfigurationManager.ConnectionStrings["BriskCargo"].ConnectionString;
// SQL with parameter
string commandString = #"
SELECT FlightNo
FROM AirLine_Flights
WHERE ALCode = #StuID AND IsActive=1
";
// use IDisposable here so it closes and garbage collects automatically
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(commandString))
{
// check the length and type here...
command.Parameters.Add("#StuID",SqlDbType.NVChar, 25).Value = StuID;
command.CommandType = CommandType.Text;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
flightsList.Add(new Airline_Flights{ FlightNo= reader["FlightNo"].ToString()});
}
}
}
}
return selectedFlights;
}
JavaScript
function Load_Regno() {
var StuID = document.getElementById('ContentPlaceHolder1_cmbAirlines').value;
$.ajax({
type: "POST",
contentType: "application/json",
url: "AirlinesDropDown.asmx/Loadetails",
data: {StuID: StuID},
dataType: "json"
})
.done(function(data) {
// verify data
alert(JSON.stringify(data));
// or
console.log(data);
var theDropDown = $("ContentPlaceHolder1_cmbFlightNo");
theDropDown.html(""); // clear old options
var options = [];
$.each(data.d, function(key, value) {
var opt = ("<option></option>").val(value.FlightNo).html(value.FlightNo))
options.push(opt);
});
$.each(options,function(v){theDropDown.append(v);});
})
.fail(function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.status == 0) {
alert('Check Your Network.');
} else if (XMLHttpRequest.status == 404) {
alert('Requested URL not found.');
} else if (XMLHttpRequest.status == 500) {
alert('Internal Server Error.');
} else {
alert('Unknown Error.\n' + XMLHttpRequest.responseText);
}
}
});
return false;
}

I want to redirect from login.aspx to address.aspx if the user insert the correct username and password

This is the WebMethod in login.aspx
[WebMethod]
public static void logedin(string uname, string password)
{
tbl_user_login objLogedin = new tbl_user_login();
DataTable dtb = new DataTable();
dtb = objLogedin.loginUser(uname, password);
//result=dtb.Columns[0].ToString();
if (dtb.Rows.Count > 0)
{
Response.Redirect("http://localhost:26430/address.aspx");
//Server.Transfer("http://localhost:26430/address.aspx");
}
else {
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
}
}
This is the database code of user_login.cs class file
public DataTable loginUser(string loginid,string passwrd)
{
DataTable dtb = new DataTable();
SqlConnection con = connect.startConnection();
try {
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from tbl_user_login where loginid=#loginid AND passwrd=#passwrd";
cmd.Parameters.AddWithValue("#loginid", loginid);
cmd.Parameters.AddWithValue("#passwrd", passwrd);
SqlDataAdapter adt = new SqlDataAdapter(cmd);
adt.Fill(dtb);
}
catch (Exception ex) {
connect.closeConnection(con);
}
connect.closeConnection(con);
return dtb;
}
This is the angularJs function which is called when user click the login button
$scope.register = function () {
var uname = $scope.name;
var idtype = $scope.idtype;
var userid = "";
if (idtype == 1) {
var userid = $scope.email;
}
else {
if (idtype == 2) {
var userid = $scope.mobile;
}
}
var passwrd = $scope.passwrd;
$.ajax({
type: 'POST',
url: siteUrl + '/registration.aspx/registerUser',
data: JSON.stringify({ loginId: userid, password: passwrd, Verified: 0, IdType: idtype, UserName: uname }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
alet("Succeddfully Inserted");
},
failure: function (data, status) {
alert("Failed");
},
error: function (data, status) {
alert("Please provide a valid email address");
},
});
My question is: the Response.Redirect function is not working and showing red underlined with a pop up as Response does not exist in the current context, and also the else part is not working
$scope.register = function () {
var uname = $scope.name;
var idtype = $scope.idtype;
var userid = "";
if (idtype == 1) {
var userid = $scope.email;
}
else {
if (idtype == 2) {
var userid = $scope.mobile;
}
}
var passwrd = $scope.passwrd;
$.ajax({
type: 'POST',
url: siteUrl + '/registration.aspx/registerUser',
data: JSON.stringify({ loginId: userid, password: passwrd, Verified: 0, IdType: idtype, UserName: uname }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
alet("Succeddfully Inserted");
},
failure: function (data, status) {
alert("Failed");
},
error: function (data, status) {
alert("Please provide a valid email address");
},
});
Instead of Response.Redirect return success message from WebMthod and redirect through call back.
public static string logedin(string uname, string password)
{
tbl_user_login objLogedin = new tbl_user_login();
DataTable dtb = new DataTable();
dtb=objLogedin.loginUser(uname, password);
//result=dtb.Columns[0].ToString();
if (dtb.Rows.Count > 0)
{
return "valid";
}
else
{
return "invalid";
}
}
In success callback
success : function(response) {
if(response.d == 'valid') {
window.location('address.aspx');
}
else {
alert('Invalid username or password');
}
}
It is better to use Angular $http. And in the success section add redirect like the bellow:
$http({
url: "/registration.aspx/registerUser",
method: "POST",
data: {loginId: userid, password: passwrd, Verified: 0, IdType: idtype, UserName: uname}
}).success(function(data, status) {
$scope.data = data;
// redirect
$window.location='http://localhost:26430/address.aspx';
}).error(function(data, status) {
$scope.status = status;
});
Do not forget to inject $http and $window in your controller to make it work correctly.

Cannot get Jquery autocomplete to work in ASP.NET MVC

I cannot get autocomplete to work. I suspect this is because of my declaration of the URL in the Jquery method. How can I fix this issue?
This is the method in the HomeController:
public JsonResult Autocomplete(string term)
{
string connectionString = ConfigurationManager.ConnectionStrings["AbintegroModelContext"].ConnectionString;
List<string> CompanyName = new List<string>();
string query = string.Format("select distinct CompanyName from CompanyTable where CompanyName like '%{0}%'", term);
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
CompanyName.Add(reader["CompanyName"].ToString());
}
}
}
return Json(CompanyName, JsonRequestBehavior.AllowGet);
}
this is the Index view:
<body>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-ui-1.8.24.js"></script>
<script>
$(function () {
$("#CompanyName").autocomplete({
source: function (request, response) {
var param = { companyName: $('#CompanyName').val() };
$.ajax({
url: '#Url.Action("Autocomplete", "Home")',
data: JSON.stringify(param),
datatype: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
var err = eval("(" + XMLHttpRequest.responseText + ")");
alert(err.Message)
console.log("Ajax Error!");
}
});
},
minLength: 2 //min legth of textbox input
});
});
</script>
...later on in the same view I have the html helper textbox CompanyName.
#Html.TextBox("CompanyName", null, new { #class = "indexTextbox" })
I haven't tried re-creating this problem on my end.
Have you used your browser's code inspector to see if any errors are returned?
Also you may try placing the jquery code inside a $(document).ready() function to see if that helps.

Client side error TypeError: a is undefined

I get data from Webmethod & it need to bind to a table.But my Jquery function not success.Not call webmethod because of Ajax call error.
My Webmethod is
[WebMethod, ScriptMethod]
public static List<UploadedFiles> GetAllUploadedFiles()
{
List<UploadedFiles> UploadedFilesDetails = new List<UploadedFiles>();
try
{
SqlCommand comGetAllFiles = new SqlCommand("SP_GetAllUploadedFiles", conDB);
comGetAllFiles.CommandType = CommandType.StoredProcedure;
if (conDB.State == ConnectionState.Closed)
conDB.Open();
SqlDataReader rdr = comGetAllFiles.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
foreach (DataRow r in dt.Rows)
{
UploadedFilesDetails.Add(new UploadedFiles
{
Id = (int)r["Id"],
UserId =(Guid)r["UserId"],
FilePath = r["FilePath"].ToString(),
Date =(DateTime) r["Date"]
});
}
}
catch(Exception ee)
{
}
finally
{
conDB.Close();
}
return UploadedFilesDetails;
My Ajax Function
<script>
$(function () {
LoadUploadFiles();
});
function LoadUploadFiles() {
var url = '<%=ResolveUrl("WebMethods.aspx/GetAllUploadedFiles") %>';
$.ajax({
url: url,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (Result) {
alert("x");//<-- This alert firing
$.each(Result.d, function (key, value) {
alert(Result.d); //<-- Thisone not firing
$("#uploaddata").append($("<table><tr></tr></table>").val
(value.Id).html(value.FilePath));
});
},
error: function (e, x) {
alert(x.ResponseText);
}
});
}
</script>

jQuery Autocomplete Not Working on Hosted Site

I am using the following code for autocompleting search textbox in my website. The code is working fine on localhost but when the site is hosted the "error" box pops up.
Script:
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Index.aspx/GetAutoCompleteData",
data: "{'location':'" + document.getElementById('ContentPlaceHolder1_txtSearch').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
and the function code is:
[WebMethod]
public static List<string> GetAutoCompleteData(string location)
{
List<string> result = new List<string>();
string connect = #"
Data Source=jaipurrooms.db.11458954.hostedresource.com; Initial Catalog=jaipurrooms;
User ID=xyz;
Password=xyz;";
using (SqlConnection con = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT Location from Details where Location LIKE '%'+#location+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#location", location);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["Location"].ToString());
}
return result;
}
}
}
I think you have to check your url in ajax request. Try to use the following syntax :
url: "./Index.aspx/GetAutoCompleteData",

Categories

Resources