JSON stringify on lists in C# web form - javascript

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

Related

Passing an array Of Objects Into An MVC .net core Controller Method Using jQuery Ajax

am using .netcore 1.1 , Visual studio 2017 , Jquery version = "3.2.1"
,am trying to make the MVC controller to get data from my page ,
i have 2 arrays in java , one is an array of Object (model view) and one is an array of strings
objects array always return error 400 (bad request)
2- string array ,always send null to the controller
i followed the below answers with no success
https://stackoverflow.com/a/13255459/6741585
and
https://stackoverflow.com/a/18808033/6741585
below is my chtml page
//#region send data back t oserver
$('#Savebtn').click(function () {
console.log(editedRows);
var UpdatedRows = JSON.stringify({ 'acActivityed': editedRows });
console.log(UpdatedRows);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/acActivity/Edit",
//traditional: true,
data: UpdatedRows ,
dataType: "json",
success: function (data) {
// here comes your response after calling the server
alert('Suceeded');
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error : " + jqXHR.responseText);
}
});
});
//#endregion
//#region deleted all selected
$('#DeleteSelectedbtn').on('click', function () {
if (confirm("Are you sure to delete All Selected ?????")) {
var selectedData = [];
var selectedIndexes;
selectedIndexes = grid.getSelectedRows();
jQuery.each(selectedIndexes, function (index, value) {
selectedData.push(grid.getDataItem(value).id);
});
console.log(selectedData);
var SelectedIds = selectedData.join(',') ;
console.log(SelectedIds);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/acActivity/DeleteSelected",
data: JSON.stringify({ "ids": SelectedIds }),
dataType: "json",
success: function (data) {
grid.render();
},
error: function (err) {
alert("error : " + err);
}
});
}
});
//#endregion
and both do have data as below console shots
the selected ID's one
my Controller
this one should expect the list of object and always return bad request ,
[HttpPost]
[ValidateAntiForgeryToken]
//public jsonResult Edit( List<acActivitytbl> acActivityed)
public ActionResult Edit( List<acActivitytbl> acActivityed)
{
foreach (acActivitytbl it in acActivityed)
{
logger.Log(LogLevel.Info, it.ID);
logger.Log(LogLevel.Info, it.Name);
logger.Log(LogLevel.Info, it.IsActive);
}
//return View(acActivityed);
return Json(new { success = true, responseText = "end of Page" });
}
that one should expect the delimited string ,but always receive null
public ActionResult DeleteSelected(string ids)
{
try
{
char[] delimiterChars = { ' ', ',', '.', ':', ' ' };
string[] words = ids.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
if (words != null && words.Length > 0)
{
foreach (var id in words)
{
bool done = true; //new acActivitiesVM().Delete(Convert.ToInt32(id));
logger.Log(LogLevel.Info, " acActivities ID {0} is Deleted Scussefully ", id);
}
return Json(new { success = true, responseText = "Deleted Scussefully" });
}
return Json(new { success = false, responseText = "Nothing Selected" });
}
catch (Exception dex)
{
..... removed to save space
});
}
}
i know there is something missing here ,but i cannot find it ,any help in that ??

List change to the json format

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

how to pass dynamically created options in multi select box to MVC controller

Please help. I'm using MVC, razor 3, jquery.
I dynamically create a multi select box when a dropdown selection changes. I bind the multiple selection to a List in my model. And it works, except it passes me the list of selected indice, instead of a list of the selected text. I want selected text, not index of the list. I set the value as text, but I have no luck.
if I manually create the list, everything works. How do I pass a list of selected options back to the controller?
I have this div in my view:
<div class="row-fluid" id="divAvailableAssemblies" hidden ="hidden">
<label class="span4">Available Assemblies:</label>
<select multiple="multiple" class="span8 ui-corner-all" id="Request_SelectingAssemblies" name="Request.SelectingAssemblies">
#*<option value="test">test</option>
<option value="test2">test2</option>*#
</select>
</div>
Here my jquery:
<script type="text/javascript">
$(function () {
$('#ddPartsToCreate').live('change',function () {
var selectedPart = this.value;
if (selectedPart < 6 || $("#txtOrderNumber").val()=="")
{
$("#divAvailableAssemblies").attr("hidden", "hidden");
return;
}
$("#divAvailableAssemblies").removeAttr("hidden");
$.ajax({
type: 'POST',
url: '#Url.Action("GetSelectingAssembliesFromOrder", "Home")',
data: JSON.stringify({ orderNumber: $("#txtOrderNumber").val() }),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
async: false,
success: function (response) {
var returnedData = JSON.parse(response);
var selectingAssemblies = $("#Request_SelectingAssemblies");
selectingAssemblies.empty();
for (var assembly in returnedData)
{
//selectingAssemblies.append($('<option >', { value: assembly }).text(returnedData[assembly].Text)).hide().show();
//selectingAssemblies.append($('<option value=' + assembly + '>' + returnedData[assembly].Text + '</option>'));
//selectingAssemblies.append($('<option >', { value: assembly, text: returnedData[assembly].Text }));
//selectingAssemblies.append($('<option></option>').val(assembly).html(returnedData[assembly].Text));
//$("#Request_SelectingAssemblies").append($('<option>', { value: assembly }).text(returnedData[assembly].Text));
//$("#Request_SelectingAssemblies").append($('<option>', { value: assembly }).text(returnedData[assembly].Text));
//$('<option />', { value: assembly, text: returnedData[assembly].Text }).appendTo(selectingAssemblies);
selectingAssemblies.append($('<option></option>').val(assembly).html(returnedData[assembly].Text));
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
in the backend, I generate JSON:
foreach (var assembly in pr.ShipParts)
{
sb.Append(String.Format(",{{\"Text\":\"{0}\", \"Value\":\"{1}\"}}", assembly.Mark.ToString(), assembly.Mark.ToString()));
availableAssemblies.Add(assembly.Mark.ToString());
}
I bind the multiple selection(Request_SelectingAssemblies) with this property in my model:
public List<String> SelectingAssemblies
{
get
{
return _SelectingAssemblies;
}
set
{
_SelectingAssemblies = value;
}
}
private List<String> _SelectingAssemblies = new List<string>();
When it gets to my action in the controller, SelectingAssemblies has index instead of the actual text. But I set the value of each option as text. If I set the option manually, they will show in source page and return the text. But since I dynamically create the options, they don't show in source page. I don't know how I can make MVC understand dynamic data.
In the picture, the list of CX001, RBX001, RBX002 is dynamically created. if I hit F12 in IE, I will see them created correctly in the DOM. If I choose CX001 and RBX002, SelectionAssembies will have 0 and 2.
Thanks
This is the latest and working code, thanks to #StephenMuecke:
<script type="text/javascript">
$(function () {
$('#ddPartsToCreate').live('change',function () {
var selectedPart = this.value;
if (selectedPart < 6 || $("#txtOrderNumber").val()=="")
{
$("#divAvailableAssemblies").attr("hidden", "hidden");
return;
}
$("#divAvailableAssemblies").removeAttr("hidden");
$.ajax({
type: 'POST',
url: '#Url.Action("GetSelectingAssembliesFromOrder", "Home")',
data: JSON.stringify({ orderNumber: $("#txtOrderNumber").val() }),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
async: false,
success: function (response) {
var returnedData = JSON.parse(response);
var selectingAssemblies = $("#Request_SelectingAssemblies");
$.each(returnedData, function (index, item) {
selectingAssemblies.append($('<option></option>').val(item.Value).html(item.Text));
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
public ActionResult GetSelectingAssembliesFromOrder(String orderNumber)
{
return Json(model.GetSelectingAssembliesFromOrder(orderNumber), JsonRequestBehavior.AllowGet);
}
public String GetSelectingAssembliesFromOrder(String orderNumber)
{
//...
StringBuilder sb = new StringBuilder();
sb.Append("[");
foreach (var assembly in pr.ShipParts)
{
string assemblyName = assembly.Mark.Trim();
sb.Append(String.Format(",{{\"Text\":\"{0}\", \"Value\":\"{1}\"}}", assemblyName, assemblyName));//JSON to build the list
//...
}
sb.Append("]");
sb.Remove(1, 1);//remove extra comma
_db.SaveChanges();
return sb.ToString();
}

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

Categories

Resources