I have a wcf service used to populate cascading drop down list in a ASPX page in IIS 7. The drop down list gets thousands of empty option tags but no data. The service does not throw an error. The entire solution runs in IDE on desktop but the service is not working correctly when deployed on IIS. I suspect it is an IIS issue but can not identify it.
<snippet from aspx page>
<asp:DropDownList ID="ddCommercialServicesSiteName" runat="server" Width="150"></asp:DropDownList>
<ajaxToolkit:CascadingDropDown
ID="cddCommercialServicesSiteName" TargetControlID="ddCommercialServicesSiteName"
PromptText="Select" PromptValue="" Category="siteID"
ServicePath="~/ServiceDropDown.svc" ServiceMethod="GetCommercialSites"
LoadingText ="Loading..." runat="server"/>
<!-- ServiceDropDown.svc code -->
<%# ServiceHost Language="C#" Debug="true" Service="ReportDashboard.ServiceDropDown" CodeBehind="ServiceDropDown.svc.cs" %>
public List GetCommercialSites(string knownCategoryValues, string contextKey)
{
List sites = new List();
if (contextKey == null)
{
return sites;
}
string query = #"select DISTINCT ContactName AS Site , id from sites";
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
cmd.Connection = con;
cmd.Parameters.Add("#account", SqlDbType.VarChar).Value = contextKey.ToString();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
sites.Add(new CascadingDropDownNameValue
{
name = reader[0].ToString(),
value = reader[1].ToString(),
});
}
reader.Close();
con.Close();
}
}
return sites;
}
Try this approach to retrieve values from the Reader.
List<MyModelClass> result = new List<MyModelClass>();
while (reader.Read())
{
object[] values = new object[3];
reader.GetValues(values);
MyModelClass model = new MyModelClass();
model.ID = values[0].ToString();
model.ValueProperty = values[1].ToString();
model.ValueProperty2 = values[2].ToString();
result.Add(model);
}
In your View/aspx run a jQuery to populate your dropdown,
$("#dropdown").change(function () {
dropdown.append($("<option></option>").val("").html("Please wait ..."));
$.ajax({
url: "/api/CascadingData/GetSomeData/",
type: "GET",
dataType: "json",
data: { Id: Id },
success: function (d) {
dropdown.empty(); // Clear the list, including the please wait option
dropdown.append($("<option></option>").val('').html("Select an option..."));
$.each(d, function (i, ModelObject) {
dropdown.append($("<option></option>").val(ModelObject.Name).html(ModelObject.Value));
});
},
error: function () {
alert("Error in $('#dropdown').change!");
}
});
}
Related
I am binding data on dropdown index change event using ajax call using asp.net web form
following my Ajax code
var e = document.getElementById("<%=ddlEducation.ClientID%>");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;
if (value == "0") {
$('#dvRecords').empty();
alert("Please Select Education");
return false;
}
var obj = { "iEduid": value};
var myJSON = JSON.stringify(obj);
//Filling Grid View
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'EditProfile.aspx/BINDEducationDATA',
data: myJSON,
dataType: 'JSON',
success: function (response) {
document.getElementById("ctl00_ContentPlaceHolder2_lblstram").value = response.d[i].eduStream
document.getElementById("ctl00_ContentPlaceHolder2_lbldescs").value = response.d[i].Edu_Description
},
error: function (xhr, status, error) {
console.log(xhr);
alert(status);
alert(error);
}
});
when it it executing i am getting 1st error is parsererror next i am getting error saying Unexpected token < in JSON at position 4.
above is my C# code
[WebMethod]
public static List<EduDesc> BINDEducationDATA(string iEduid)
{
List<EduDesc> details = new List<EduDesc>();
DataTable dtManager = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
cmd = new SqlCommand("Select Edu_Stream,Edu_Description from tbl_education WHERE ID='" + iEduid + "'", con);
da.SelectCommand = cmd;
da.Fill(dtManager);
}
foreach (DataRow dtrow in dtManager.Rows)
{
EduDesc logs = new EduDesc();
logs.Edu_desc = (dtrow["Edu_Description"].ToString());
logs.eduStream = dtrow["Edu_Stream"].ToString();
details.Add(logs);
}
return details;
}
any help will appreciated.
There are a couple areas of concern.
foreach (DataRow dtrow in dtManager.Rows)
{
EduDesc logs = new EduDesc();
// - extra parentheses.
// - here you use logs.Edu_desc but in 'success' (below) you use Edu_Description.
logs.Edu_desc = (dtrow["Edu_Description"].ToString());
logs.eduStream = dtrow["Edu_Stream"].ToString();
details.Add(logs);
}
success: function (response) {
// here you're looking for [i], but what is i? you need an integer.
document.getElementById("ctl00_ContentPlaceHolder2_lblstram").value =
response.d[i].eduStream
document.getElementById("ctl00_ContentPlaceHolder2_lbldescs").value =
response.d[i].Edu_Description
},
In the success function, do a console.log(d) to double-check the results.
hth.
Firstly I'm new to Angular JS and trying to explore the language, So I'm not fluent...:)
I'm trying to do a simple call to a stored procedure from a web service by collecting the data passed from URL. No data is being fetched.
I know I'm messing it up somewhere, can you guys please point me out where. :)
This would be my URL:
http://localhost:2752/ProjectName/PageName.aspx?Id=24
This is my script where I'm fetching the data from the URL and passing it to the service:
/// <reference path="../angular.min.js" />
window.params = function () {
var params = {};
var param_array = window.location.href.split('?')[1].split('&');
for (var i in param_array) {
x = param_array[i].split('=');
params[x[0]] = x[1];
}
return params;
} ();
var app = angular.module("myModule", []);
app.controller("myController", function ($scope, $http) {
$http.post('Services/GetCompletePropDetailsService.asmx/GetPropertyDetailsList' ,window.params.Id)
.then(function (response) {
$scope.PropertyDetailsListitem = response.data;
});
});
And this is my service:
[WebMethod]
public void GetPropertyDetailsList(String submittedData)
{
List<PreviewDataClass> listPropertyDetails = new List<PreviewDataClass>();
string cs = ConfigurationManager.ConnectionStrings["DBPCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spPreviewDataUserId", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter username = new SqlParameter("#UserId", submittedData);
cmd.Parameters.Add(username);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
PreviewDataClass PropertyDetails = new PreviewDataClass();
PropertyDetails.FullName = Convert.ToString(rdr["FullName"]);
listPropertyDetails.Add(PropertyDetails);
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(listPropertyDetails));
}
Any better method to achieve the same is appreciated
I want to get data from the database based on the text of that link on click of the link but getting undefined alert message.
I'm new to jquery so please help me out with this if anybody can. Thanks in advance.
here is the code snippet
jquery
<script type="text/javascript">
var name;
$(function () {
$("[id*=Menu] td a").click(function () {
name=$(this).text().trim();
GetRecords();
//alert(name);
});
});
function GetRecords() {
$("#loader").show();
$.ajax({
type: "POST",
url: "kioskstore.aspx/GetPrice",
data: '{name: ' + name + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var productsInfo = xml.find("Products_Info");
productsInfo.each(function () {
var customer = $(this);
$(".price").html(customer.find("Products_Price").text().trim());
});
$("#loader").hide();
}
</script>
asp.net
<div style="margin-top:25px;height:40px;float: left;margin-left:40px;font-family:cursive;font-size:24px;color:#ffe476;">
<asp:Label runat="server" CssClass="price" Text=""></asp:Label>
</div>
and the code behind C#
[WebMethod]
public static string GetPrice(string name)
{
return GetPriceData(name).GetXml();
}
public static DataSet GetPriceData(string name)
{
string query = "select * from Product_Info where Product_Name=#pname";
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#pname", name);
//cmd.Parameters.Add("#PageCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
return GetData(cmd);
}
private static DataSet GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["mycon"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds, "Product_Info");
return ds;
}
}
}
}
I think you are missing enclosing quotes for string.
Use
data: '{name: "' + name + '"}'
instead of
data: '{name: ' + name + '}'
Responding to your comment:
That message means you are requesting an incorrect URL. Please try with this.
url:document.location + '/GetPrice'
Please confirm whether your request is going to the correct URL. You can use the network monitor component of a browser development tools or an HTTP proxy like Fiddler. If you have chrome, you can check this using the Network tab of the Development Tools. Additionally you can make use of a chrome plugin called Postman to invoke HTTP request to check if they are working or not.
if you are calling from the same page?
Here I have two dropdownlists. First one to display the list of countries and the second to list the states value for selected country from first. The list of values are populated from
properly but in the dropdownlist, the values are not populated.
jQuery:
$(document).ready(function () {
$("#Country").change(function () {
var Id = $('#Country option:selected').attr('value');
$("#Region").empty();
$.getJSON("/ControllerName/GetRegionList",{ ID: Id },
function (data) {
jQuery.each(data, function (key) {
$("#Region").append($("<option></option>").val(ID).html(Name));
});
});
});
});
View :
#Html.DropDownList("Country", new SelectList(Model.CountryList, "Value", "Text", Model.CountryList.SelectedValue))
#Html.DropDownList("Region", new SelectList(Model.RegionList, "Value", "Text", Model.RegionList.SelectedValue))
Controller:
public List<Region> GetRegionList(int ID)
{
int countryid = ID;
AddressModel objmodel = new AddressModel();
List<Region> objRegionList = new List<Region>();
objRegionList.Add(new Region { ID = "0", Name = " " });
if (countryid != 0)
{
countryid = Convert.ToInt32(ID);
SqlCommand cmd = new SqlCommand("USP_ProcedureName", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Id", countryid);
cmd.Parameters.AddWithValue("#Mode", "Region");
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr["RegionId"].ToString() != "")
{
objRegionList.Add(new Region { ID = dr["RegionId"].ToString(), Name = dr["Name"].ToString() });
}
}
dr.Close();
con.Close();
}
return objRegionList;
}
What is the mistake in my code.? Any Suggestions.
EDIT : Added the snapshot
In ASP.NET MVC controller actions must return ActionResults. In your case you could return JSON:
public ActionResult GetRegionList(int id)
{
var objRegionList = new List<Region>();
objRegionList.Add(new Region { ID = "0", Name = " " });
if (countryid != 0)
{
int countryid = ID;
using (var conn = new SqlConnection("YOUR CONNECTION STRING COMES HERE"))
using (var cmd = conn.CreateCommand())
{
con.Open();
cmd.CommandText = "USP_ProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Id", countryid);
cmd.Parameters.AddWithValue("#Mode", "Region");
using (var dr = cmd.ExecuteReader())
{
while (dr.Read())
{
if (dr["RegionId"].ToString() != "")
{
objRegionList.Add(new Region
{
ID = dr["RegionId"].ToString(),
Name = dr["Name"].ToString()
});
}
}
}
}
}
return Json(objRegionList, JsonRequestBehavior.AllowGet);
}
Notice that I have also cleared your code from unused variables and unnecessary Convert.ToInt32 calls and most importantly wrapped IDisaposable resources such as SQL connections, commands and data readers in using statements to avoid leaking resources.
Then include the url of the controller action as a data-* attribute on the first dropdown to avoid ugly hardcoding it in your javascript and breaking when you deploy your application in IIS in a virtual directory:
#Html.DropDownList(
"Country",
new SelectList(Model.CountryList, "Value", "Text", Model.CountryList.SelectedValue),
new { data_url = Url.Action("GetRegionList", "ControllerName") }
)
finally adapt (simplify) your javascript:
$('#Country').change(function () {
var regionDdl = $('#Region');
regionDdl.empty();
var id = $(this).val();
var url = $(this).data(url);
$.getJSON(url, { id: id }, function (data) {
$.each(data, function (index, region) {
regionDdl.append(
$('<option/>', {
value: region.ID,
html: region.Name
})
);
});
});
});
I have a text box in aspx page. from that i need to send the text of the textbox in function in Json For that i have a method in server side.
[WebMethod]
public static OfficeDetails[] BindSearchDatatable(string officename)
{
DataTable dt = new DataTable();
List<OfficeDetails> details = new List<OfficeDetails>();
using (SqlConnection con = new SqlConnection(#"Data Source=GTL--7\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("select OfficeName,City,Country from Office where OfficeName like '%" + officename + "%'", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dtrow in dt.Rows)
{
OfficeDetails Office = new OfficeDetails();
Office.OfficeName = dtrow["OfficeName"].ToString();
Office.City = dtrow["City"].ToString();
Office.Country = dtrow["Country"].ToString();
details.Add(Office);
}
}
}
return details.ToArray();
}
and in .aspx page I have
$('#btnSearch').click
(
function () {
var searchtext = $("#txtSearch").val();
alert(searchtext);
$.ajax(
{
type: "POST",
url: "Gridview.aspx/BindSearchDatatable",
data: "{officename : New}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#gvDetails").append("<tr><td>" + data.d[i].OfficeName + "</td><td>" + data.d[i].City + "</td><td>" + data.d[i].Country + "</td></tr>");
}
},
error: function (x, e) {
alert("The call to the server side failed. " + x.responseText);
}
}
);
return false;
}
);
Now my Question is I send the Parameter in data but i am getting an error The function is running well.I have tested it without parameter so its running well.so i thing some wrong things is going on passing the text value Of textbox in function.
You are sending an invalid JSON. Replace:
data: "{officename : New}"
with:
data: "{officename : 'New'}"
or even better use the JSON.stringify method which wil take care of properly encoding the values:
data: JSON.stringify({ officename : 'New' })
Also please fix your server side script and use parametrized queries because your code is vulnerable to SQL injection attacks and if you put this code into the wild, you might find yourself one day with a missing database. Oh and you really don't need any DataTables:
[WebMethod]
public static OfficeDetails[] BindSearchDatatable(string officename)
{
using (var con = new SqlConnection(#"Data Source=GTL--7\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "SELECT OfficeName, City, Country FROM Office WHERE OfficeName LIKE #officename";
cmd.Parameters.AddWithValue("#officename", "%" + officename + "%");
using (var reader = cmd.ExecuteReader())
{
var details = new List<OfficeDetails>();
while (reader.Read())
{
var office = new OfficeDetails();
office.OfficeName = reader.GetString(reader.GetOrdinal("OfficeName"));
office.City = reader.GetString(reader.GetOrdinal("City"));
office.Country = reader.GetString(reader.GetOrdinal("Country"));
details.Add(office);
}
return details.ToArray();
}
}
}
Replace:
data: "{officename : New}"
with:
data: {officename : 'New'},