I have a WebMethod in my asp.net page that returns a string that is the representation of a JSON array containing data that i want to use as source for my jquery-ui autocomplete textbox.
[WebMethod]
public static string GetCities(string cityName)
{
JArray json = new JArray(
new JObject(new JProperty("label", "label1"), new JProperty("category", "cat1"), new JProperty("value", "v1")),
new JObject(new JProperty("label", "label2"), new JProperty("category", "cat1"), new JProperty("value", "v2")),
new JObject(new JProperty("label", "label3"), new JProperty("category", "cat2"), new JProperty("value", "v3")),
new JObject(new JProperty("label", "label4"), new JProperty("category", "cat3"), new JProperty("value", "v4")));
return json.ToString();
}
javascript code:
<script type="text/javascript">
$(function () {
$("#txtCity").autocomplete({
source: function (request, response) {
var param = { cityName: $('#txtCity').val() };
$.ajax({
url: "WebForm1.aspx/GetCities",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response(data.d); //here data.d contains the json array string
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
select: function( event, ui ) {
$( "#output" ).val( ui.item.value );
return false;
},
minLength: 2//minLength as 2, it means when ever user enter 2 character in TextBox the AutoComplete method will fire and get its source data.
});
});
</script>
But my autocomplete generates an item for each character in the JSON string. I assume I'm not returning it correctly.
Figured it out,
success: function (data) {
response($.parseJSON(data.d))
},
Had to parse the JSON.
Related
I use JSON.stringify for a textbox autocomplete for a web-form. What I want to do is; autocomplete a textbox for city names by getting appropriate city names from my database. Autocomplete works after 3 letters.
The problem is; suggested city names are shown in one line. For example, when I typed are to textbox (which is named "MainContent_city") it is shown like: "Arequipa,Arecibo,Are Ostersund,Arezzo,Arendal" in one line, as one string object. What I want is to show all of those city names line by line. Such as;
Arequipa
Arecibo
Are Ostersund
Arezzo
Arendal
Below is my javascript code;
<script type="text/javascript">
$(function () {
$("#MainContent_city").autocomplete({
source: function (request, response) {
var param = { cityname: $('#MainContent_city').val() };
$.ajax({
url: "HotelAdd.aspx/GetCities",
data: JSON.stringify(param, null, param.length),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
},
minLength: 3
});
});
</script>
This is my C# code for "GetCities" method
[WebMethod]
public static List<string> GetCities(string cityname)
{
List<string> City = new List<string>();
string query = "SELECT name FROM City WHERE name LIKE #SearchText + '%'";
//Note: you can configure Connection string in web.config also.
SqlCommand cmd = new SqlCommand(query, connection);
cmd.Parameters.AddWithValue("#SearchText", cityname);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds2 = new DataSet();
adapter.Fill(ds2);
for(int i=0; i<ds2.Tables[0].Rows.Count; i++)
{
City.Add(ds2.Tables[0].Rows[i][0].ToString());
}
return City;
}
Data is contained in data.d.
Change this response($.map(data, function (item) to response($.map(data.d, function (item)
success: function (data)
{
response($.map(data.d, function (item) {
return
{
value: item
}
}))
},
I want to change list to json format. How can I do?
var db = new TelephoneBookDataContext();
List<string> Capitals = (from U in db.Users
where U.Name.ToLower().StartsWith(name.ToLower())
select U.Name).ToList();
return Capitals;
Java script part I cant get as such this code part
$("document").ready(function () {
$("#<%= txtSearch.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: "Show.aspx/GetName",
data: "{'name':'" + $("#<%= txtSearch.ClientID %>").val() + "'}",
dataType: "json",
type: "POST",
success: function (data) {
response(data.d);
},
error: function (result) {
console.log(result);
}
});
},
minLength: 2
});
});
First Add Name space
using System.Web.Script.Serialization;
Then use JavaScriptSerializer class
JavaScriptSerializer jss = new JavaScriptSerializer();
string output = jss.Serialize(ListOfMyObject);
your List is of String Type so you might need this try below if above
donot work.
string[][] ArrayCapitals = Capitals.Select(x => new string[]{x}).ToArray();
string json = JsonConvert.SerializeObject(ArrayCapitals );
I am trying to fetch company name in textbox as autocomplete. When I run my project, Ajax will call the success function, and the record is also fetched correctly, but there are no autocomplete suggestions in the textbox.
My view is:
$("#idcompanyname").autocomplete({
source: function (request, response) {
var customer = new Array();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("Companymap", "admin")',
data: "{'term':'" + document.getElementById('idcompanyname').value + "'}",
dataType: "json",
success: function (data) {
alert(data)
response($.map(data, function (v, i) {
var text = v.vcCompanyName;
alet(text)
if (text && (!request.term || matcher.test(text))) {
return {
label: v.vcCompanyName,
value: v.kCompanyId
};
}
}));
},
error: function(result) {
alert("No Match");
}
});
}
});
}
Here is Method on controller:
var query = db.tbaccounts.Where(t => t.vcCompanyName.ToLower()
.StartsWith(term)).ToList();
List<string> lst = new List<string>();
foreach (var item in query)
{
lst.Add(item.vcCompanyName);
}
return Json(lst, JsonRequestBehavior.AllowGet);
Here is the referred Javascript:
<script src="~/script/jquery-2.0.3.js"></script>
<script src="~/script/jquery-ui.js"></script>
<script src="~/js/jquery-1.10.2.js"></script>
<script src="~/js/jquery-ui.js"></script>
Please try removing
~/script/jquery-2.0.3.js
from the script references in your application, and that should work for you....
I have the following JavaScript code to do an autocomplete:
$("#Technology2_Tag").autocomplete({
source: function (request, response) {
$.ajax({
url: "#Url.Content("~/Switch/AutoComplete2")",
dataType: "json",
minLength: 2, delay: 2000,
data: {
term: request.term,
SearchBy: $("#ChoiceTag").prop("checked") ? $("#ChoiceTag").val() : $("#ChoiceName").val(),
},
success: function (data) {
response(data);
}
});
},
});
And I am returning the autocomplete records as JSON:
public ActionResult AutoComplete2(string term, string SearchBy)
{
if (SearchBy == "Tag")
{
var tech = repository.AllFindTechnolog(term).OrderBy(p => p.Tag).Select(a => new { label = a.Tag }).ToList();
return Json(tech, JsonRequestBehavior.AllowGet);
}
else
{
var tech = repository.FindActiveResourceByName(term, true).OrderBy(p => p.RESOURCENAME).Select(a => new { label = a.RESOURCENAME }).ToList();
return Json(tech, JsonRequestBehavior.AllowGet);
}
}
But my question is how I can show a dialog the contains additional info about the record, when the user hovers over an autocomplete record.
what i am thinking of is as follows:
when the user hovers over any autocomplete record, to fire a JavaScript function.
the function calls an action method, that returns JSON.
to build the dialog box using the returned JSON object.
First you need to create a div let's say with the id=mydiv which can be a dialog. Initialize it as a dialog.
Then in your autocomplete use focus event. Which will handle an Ajax function which will call an Action (this action can return a Partial view) and will fill your div with the description.
$("#mydiv").dialog();
$ ("#Technology2_Tag").autocomplete({
source: function (request, response) {
$.ajax({
url: "#Url.Content("~/Switch/AutoComplete2")",
dataType: "json",
minLength: 2, delay: 2000,
data: {
term: request.term,
SearchBy: $("#ChoiceTag").prop("checked") ? $("#ChoiceTag").val() : $("#ChoiceName").val(),
},
success: function (data) {
response(data);
}
});
},
focus: function(event,ui){
var element =ui.item.val;
$.ajax({
url: "#Url.Content("~/Switch/ActionDescription")",
dataType: "json",
data: {
hoverelment: element },
success: function (data) {
$('#myDiv').append(data);
$('#myDiv').show();
}
});
}
});
I gave you lines, you have to create another action which will receive a parameter, can send a partial view or just string.
public ActionResult ActionDescription(string hoverlement)
{
.........//linq queries to retrieve description by hoverelement
}
I hope it will help.
So i have list that is created dynamically as shown
Now I need a ADD button, which on click will add new item to list automatically. Help me out with this please.
Hi this is how can you retrive data using jquery
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "URL/MethodName",
data: "{}",// you can provide parameteres to your function here
dataType: "JSOn",
success: function (data) {
for (var i in data) {
alert(data[i].Id); //assign to controls
alert(data[i].Header);// assign to controls
alert( data[i].Content) ;// assign to contols
}
alert('Data fetched Successfully');
},
error: function (result) {
alert('Data not fetched ');
return false;
}
});
return false;
});
/*************************************************************************
[System.Web.Services.WebMethod]
public ActionResult Careers()
{
List<JobOpening> job = new List<JobOpening>()
{
new JobOpening{Id = 1, Header = "Job1", Content = "edde" },
new JobOpening{Id = 2,Header = "Job2", Content = "deded" },
};
}