List change to the json format - javascript

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 );

Related

JSON stringify on lists in C# web form

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
}
}))
},

Populating jquery autocomplete with data from asp WebMethod

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.

Autocomplete textbox in asp.net mvc4 using ajax and jQuery

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....

How to list autocomplete results as a link?

I am new on Ajax. I need to find how to list autocomplete results as a link. When user clicks the result should open that link. I can list the related result but I couldn't find how to add the links. It should be added somewhere in the script as a html tag. Please give me some clue how to add html link
Here is my script:
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".auto").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'question':'" + document.getElementById('txtQuestion').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error Occurred");
}
});
}
});
}
</script>
Here is the method which connects to the db and returns related results:
[WebMethod]
public static List<string> GetAutoCompleteData(string question)
{
List<string> result = new List<string>();
using (SqlConnection conn = new SqlConnection("Data Source=xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx+"))
{
using (SqlCommand cmd = new SqlCommand("SELECT Questions,Link FROM DigiQA WHERE Questions LIKE '%'+#quest+'%'", conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#quest", question);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["Questions"].ToString());
}
return result;
}
}
}
Try something like this
success: function(data) {
response($jQuery.map(data, function(item) {
return {
label: '' + item + ''),
value: item
}
}))
}

How do I get the right $.ajax data type

could you please help with this. I have the following javascript:
$('form').click(function (e)
{
if (e.target.getAttribute('id') === 'SubmitAddLevel')
{
var parent = $('#' + e.target.getAttribute('attr')),
var Data = [];
parent.find('.input').children().each(function (i, e)
{
Data.push(e.getAttribute('id') + ":" + e.value);
console.log(Data);
});
$.ajax({
type: "POST",
url: 'AjaxControls.aspx/CreateUserLevel',
//data: Data, //.join(','),
dataType: "text",
contentType: "application/json; charset=utf-8",
//error: function (er) { alert(er); },
success: function (response)
{
if (response.d === "true")
{
$("#ErrorDivAddLevel").html('Level created successfully!').fadeIn('slow');
}
else
{
$("#SuccessDivAddLevel").html('Level creation failed!').fadeIn('slow');
}
},
});
}
The result of 'Data' I got on the console is :["LevelNameAddLevel:Admin", "PriviledgeIDAddLevels:|1|2|3|4|5|6|7|"]. How do I convert this to what ajax will pass to my web menthod?
Here is the web method
<WebMethod(EnableSession:=True)>
Public Shared Function CreateUserLevel(userLevel As String, userPriviledges As String) As String
return "true"
end function
I think your Data should look something more like this:
[{"LevelNameAddLevel":"Admin"}, {"PriviledgeIDAddLevels":"|1|2|3|4|5|6|7|"}]
So you have key / value pairs inside of an array. In the request, you should then be able to fetch the data via the keys in the request.
But I'm not quite sure what this is supposed to mean : "|1|2|3|4|5|6|7|"

Categories

Resources