On my ASPX page I have the following ComboBox that should be filled from an Ajax WebMethod.
<ajaxToolkit:ComboBox ID ="cbMembers" runat="server"></ajaxToolkit:ComboBox>
The WebMethod that fills the ComboBox is called as follows:
$.ajax({
type: "POST",
url: functions.aspx/members",
data: "{SearchInput: '" + SearchInput + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var cbMembers = $("[id*=cbMembers]");
$.each(r.d, function () {
cbMembers.append( -- My problem is here -- );
})
}
});
WebMethod
List<ListItem> members = new List<ListItem>();
...
if (Reader.HasRows)
{
while (Reader.Read())
{
members.Add(new ListItem
{
Value = HttpUtility.HtmlEncode((string)(Reader["name"])),
Text = HttpUtility.HtmlEncode((string)(Reader["name"]))
});
}
}
return members;
...
The data is retrieved correctly from the WebMethod. I tested it. But my problem is to fill the list items in the ComboBox. Any advice?
success: function (r) {
var cbMembers = $("[id*=cbMembers]");
$.each(r.d, function () {
cbMembers.append( -- How to append the data here? --);
})
}
Try this
$.each(r.d, function () {
cbMembers.append($("<option>",{value:"1",text:"Gloria"}));
})
Try this
$.each(r.d, function () {
cbMembers.append($("<option></option>").val(this['Value']).html(this['Text']));
}
Related
Anyone can tell me how can i use tokenizing in auto-complete for multiple selection, I am make you sure that, i want only with asp.net web from web service
My Code:
$(function () {
// Web servcice javascript code for City
$("[id*=ctl00_ContentMain_TextBoxSkills]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/WebServices/WebServiceSkills.asmx/GetAutoCompleteData")%>',
data: "{ 'username': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.d.length > 0) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
};
}))
} else {
response([{ label: 'No results found.', val: -1 }]);
}
}
});
},
select: function (e, u) {
if (u.item.val == -1) {
return false;
}
}
});
});
I want to use a web service to fetch data from database and show on front-end for multiple selection
Web Service:
DataTable dt = userRegistrationHelper.GetSkillsList(username);
DataRow[] rows = null;
rows = dt.Select(string.Format("SkillName = {0}", username));
string[] result = new string[rows.Length];
for (int i = 0; i <= rows.Length - 1; i++)
{
result[i] = rows[i]["SkillName"].ToString();
}
return result;
Autocomplete with multiple words or values with comma separated
$(function () {
$("[id*=ctl00_ContentMain_TextBoxSkills]").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<%=ResolveUrl("~/WebServices/WebServiceSkills.asmx/GetAutoCompleteData")%>',
data: "{'username':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("[id*=ctl00_ContentMain_TextBoxSkills]").bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
});
<asp:Button ID="Button1" runat="server" Text="Submit" />
<script>
$(document).ready(function () {
$("#Button1").click(function () {
var list = [];
var a= $("#TextBox1").val();
var b= $("#TextBox2").val();
var count = a* b;
list.push('test');
for (var i = 1; i <= count; i++) {
var item = $("#DropDownList_" + i + "_").find(":selected").text();
list.splice(i, 0, item);
console.log(list.join());
alert(list[i]);
}
});
});
</script>
Hello guys first time at the stack! I have this jquery code that get all choices of dropdown list and store it in array.
I want pass this array to c# so I can store the values in DB, please help.
You can simply do this using jQuery ajax:-
var dataToSend = { "Data": list};
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/SaveData",
data: JSON.stringify(dataToSend),
success: function (msg) {
//success data if any
},
error: function (msg) { //handle error here }
});
Add this method in your page behind (Default.aspx.cs):-
[WebMethod]
public static void SaveData(string[] Data)
{
//Save data to DB
}
In my Ajax function i tried to pass a int Parameter to the Webmethod but it's not success.
Here i paste my code
Ajax Function
$('#drpChurchNames').on('change', function () {
//alert($(this).val());
LoadFathersToChurch(churchId)
});
function LoadFathersToChurch(churchId) {
var url = '<%=ResolveUrl("WebMethods.aspx/GetFatherNames") %>';
$.ajax({
url: url,
type: "GET",
dataType: "json",
data:'{ Id: " '+churchId +' "}',
contentType: "application/json; charset=utf-8",
success: function (Result) {
$.each(Result.d, function (key, value) {
$("#drprevfather").append($("<option></option>").val
(value.Id).html(value.FatherName));
});
},
error: function (e, x) {
alert(x.ResponseText);
}
});
}
Here is my WebMethod
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static List<FatherNames> GetFatherNames(int ChurchId)
{
List<FatherNames> FathersList = new List<FatherNames>();
try
{
SqlCommand comChurchNames = new SqlCommand("GetFathers", conDB);
comChurchNames.CommandType = CommandType.StoredProcedure;
comChurchNames.Parameters.Add("#Id", SqlDbType.Int);
comChurchNames.Parameters["#Id"].Value = ChurchId;
if (conDB.State == ConnectionState.Closed)
conDB.Open();
SqlDataReader rdr = comChurchNames.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
foreach (DataRow r in dt.Rows)
{
FathersList.Add(new FatherNames
{
Id = (int)r["Id"],
FatherName = r["FatherName"].ToString()
});
}
}
Here is my SP
ALTER PROCEDURE [dbo].[GetFathers]
#SelectIndexName int
AS
BEGIN
Select * from dbo.RevFathers
Where ChurchId = #SelectIndexName
END
You are passing Id as parameter and the correct is ChurchId just like webmethod signature GetFatherNames(int ChurchId).
There is the correct way:
$.ajax({
url: url,
type: "GET",
dataType: "json",
data:'{ ChurchId: " '+churchId +' "}',
contentType: "application/json; charset=utf-8",
success: function (Result) {
$.each(Result.d, function (key, value) {
$("#drprevfather").append($("<option></option>").val
(value.Id).html(value.FatherName));
});
},
error: function (e, x) {
alert(x.ResponseText);
}
});
Is your webmethod actually getting executed? If it is and you think it should be returning data, it could be that your webmethod is not returning JSON, thus jQuery may be generating and error and not firing success.
I have this in my global.asax to configure the output for both XML and JSON:
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http;
Placed in app_start
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));
GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));
I know this isn't a direct answer, but I can't post comments yet so I would have just asked the above question first about is the webmthod getting called.
function getReportGroups() {
$.ajax({
contentType: "application/json; charset=utf-8",
url: "ReportGroups.ashx",
data: {
'method': 'getReportGroups',
'projectId': '30390'
},
dataType: "json",
success: function (data) {
alert('inside success');
var i = 0;
groupName = [data[i].name];
while (data[i] != null) {
alert([data[i].name]);
alert([data[i].reportGroupId]);
$("#top-node").append("<li item-checked='true' item-expanded='true'><a href=# style=font-weight:bold>" + [data[i].name] + "</a>");
i++;
var id = [data[i].reportGroupId];
getReports(id);
}
},
error: function (result) {
alert("Error- Inside the error loop");
}
});
}
function getReports(id) {
$.ajax({
contentType: "application/json; charset=utf-8",
url: "ReportGroups.ashx",
data: {
'method': 'getReports',
'reportGroupId': id
},
dataType: "json",
success: function (data) {
alert('inside getReports success');
var i = 0;
groupName = [data[i].name];
while (data[i] != null) {
alert([data[i].name]);
i++;
}
},
error: function (result) {
alert("Error- Inside the error loop");
}
});
}
This is my code.
Here when i call the getReports(id) from the getReportGroups() with the parameter id, the id is passed as zero in the getReoprts() function. I don know whats the problem. i used an alert box to check whether the 'id' exist in the first one, it does.. I have a valid Id in the getReportsFunction. But i am getting the id as zero in the second. What am i doing wrong here ?
Problem looks like i++, you can use .each() to iterate through the data
$.each(data, function(idx, item){
alert(item.name);
alert([item.reportGroupId]);
$("#top-node").append("<li item-checked='true' item-expanded='true'><a href=# style=font-weight:bold>" + [item.name] + "</a>");
var id = [item.reportGroupId];
getReports(id);
})
Looks like you're incrementing i before calling var id = data[i].reportGroupId, where as you test the value on the first iteration (alert([data[i].reportGroupId]);).
Move i++ as the last statement of the while loop and see if this resolves your issue.
I have a simple web service with one argument :
public static string LoadComboNews(string id)
{
string strJSON = "";
DataRowCollection people = Util.SelectData("Select * from News where person = "+ id +" Order by NewsId desc ");
if (people != null && people.Count > 0)
{
//temp = new MyTable[people.Count];
string[][] jagArray = new string[people.Count][];
for (int i = 0; i < people.Count; i++)
{
jagArray[i] = new string[] { people[i]["NewsID"].ToString(), people[i]["Title"].ToString() };
}
JavaScriptSerializer js = new JavaScriptSerializer();
strJSON = js.Serialize(jagArray);
}
return strJSON;
}
on javascript I am trying to call it with parameter :
jQuery.ajax({
type: "POST",
url: "webcenter.aspx/LoadComboNews",
data: "{'id':usrid}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
combonews = eval(msg.d);
}
});
UPDATE:
usrid is dynamic
Am I doing something wrong here?
data you are sending is invalid "{'id':usrid}"
this not a valid json
probably what you wanna do is assuming usrid is a variable
"{\"id\":"+usrid+"}"
with it shoudnt you be executing this command
Select * from News where person = '"+ id +"' Order by NewsId desc
Considering id is a string
also try this
combonews = JSON.stringify(msg);
Add WebMethod to the method
[WebMethod]
public static string LoadComboNews(string id)
And try this format
$.ajax({
type: "POST",
url: "webcenter.aspx/LoadComboNews",
data: '{"id":"usrid"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
alert(msg.d);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
alert(textStatus + " " + errorThrown);
}
});
Or
data: '{"id":"' + usrid + '"}',