How to get autocomplete data correctly formatted - c#

Using .NET here's what I've got.. The right results are returned, but they're all combined together into one long string. How can I make it so I can select one item at a time from the results returned? I know my source in the javascript is configured incorrectly. Any help would be appreciated. Thanks
Code behind:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string[] GetEmails(string emailContains)
{
LoginSet logins = staticLogic.searchLogins(staticClient, new SearchCriteriaSet());
List<BaseEntry> loginList = logins.Where(x => ((LoginEntry)x).LoginEMail.Contains(emailContains)).ToList();
List<string> emails = new List<string>();
for (int i = 0; i < loginList.Count(); ++i)
{
string email = ((LoginEntry)loginList.ElementAt(i)).LoginEMail;
emails.Add(email);
}
//JavaScriptSerializer serializer = new JavaScriptSerializer();
//string json = serializer.Serialize(emails.ToArray());
return emails.ToArray();
}
UI:
<tr><td>Destination:</td>
<td>
<div class="ui-widget">
<input type="text" name="EMailReportDestination" id="EMailReportDestination" size="60" runat="server" />
</div>
</td>
</tr>
JQuery:
$('#EMailReportDestination').autocomplete({
source: function (request, response) {
$.ajax({
url: '/reports/editemailreport.aspx/GetEmails',
type: 'POST',
dataType: 'json',
data: "{'emailContains':'" + request.term + "'}",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
//console.log('autocomplete success: ' + data);
response($.map(data, function (item) {
return {
label: item,
value: item
}
}));
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("autocomplete error: " + xhr.status + ", " + thrownError);
}
});
},
minLength: 2,
select: function (event, ui) {
console.log(ui.item ? "selected: " + ui.item.label : "nothing selected, input was " + this.value);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});

I tried and I don't know array returned in data.d. try to change
response($.map(data, function (item)
to
response($.map(data.d, function (item)

Related

Widget z-index modification

I am having issue in displaying a widget inside a modal on ASP.NET MVC platform. Currently, the widget is showing at the back of my modal.
#Html.TextBoxFor(Function(model) model.Clinic, New With {.Style = "width:300px", .id = "txtClinic"})
Widget
$.widget('custom.mcautocomplete', $.ui.autocomplete, {
_create: function () {
this._super();
this.widget().menu("option", "items", "> :not(.ui-widget-header)");
},
_renderMenu: function (ul, items) {
var self = this,
thead;
if (this.options.showHeader) {
table = $('<div class="ui-widget-header" style="width:100%"></div>');
$.each(this.options.columns, function (index, item) {
table.append('<span style="padding:0 4px;float:left;width:' + item.width + ';">' + item.name + '</span>');
});
table.append('<div style="clear: both;"></div>');
ul.append(table);
}
$.each(items, function (index, item) {
self._renderItem(ul, item);
});
},
_renderItem: function (ul, item) {
var t = '',
result = '';
var term = this.term;
$.each(this.options.columns, function (index, column) {
var value = item[column.valueField ? column.valueField : index];
t += '<span style="padding:0px 4px;float:left;width:' + column.width + ';height:13px;">' + value + '</span>'
});
var $a = '<a class="mcacAnchor">' + t + '<div style="clear: both;"></div></a>';
result = $('<li style="border-bottom: solid 1px #cccccc"></li>')
.data('ui-autocomplete-item', item)
.append($a)
.appendTo(ul);
return result;
}
});
Ajax
$("#txtClinic").mcautocomplete({
showHeader: true,
columns: [{
name: 'Code',
width: '120px',
valueField: 'ClinicCode'
}, {
name: 'Clinic Name',
width: '370px',
valueField: 'Clinic'
}
],
minLength: 3,
source: function (request, response) {
$.ajax({
cache: false,
url: '/User/GetClinicAllDetails',
type: "POST",
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
ClinicCode: item.ClinicCode,
Clinic: item.Clinic
}
}));
},
error: function (response) {
swal("", response.message, "error");
}
});
}
});
All the codes are listed in my Modal View, any ideas what could went wrong?
For anyone who is having the same issue as me.
Simply add the following line to the widget portion:
$(".ui-autocomplete.ui-front.ui-menu.ui-widget.ui-widget-content").addClass("zindex9999");
In your style:
.zindex9999{z-index:9999 !important;}
The reason of doing so is because when a modal is opened, the position is set to absolute and it neglect all the existing div, by setting z-index to 9999, it actually overwrites the absolute index as the absolute index is around 9998 (I'm not sure)

Append multiple tags in text box in code behind using tagit jquery

I have a tagit auto-complete jquery which runs fine when searching case numbers. I'm trying to append some case numbers already inserted in the text box from code behind and set as individual tags for case number. It does set as a tag, but I'm unable to make individual tags as it combines all case numbers to a single tag. Below is my code.
class.cs
List<Models.Case> caseRefer = CaseCon.ViewById(SelectedCase.strId); // here I'm fetching case numbers from database with ',' for separation.
List<string> casenumbers = new List<string>();
if (caseRefer[0].ReferCases!=null)
{
if (caseRefer[0].ReferCases != null)
{
casenumbers = caseRefer[0].ReferCases.Split(',').ToList(); // here I'm spiting case numbers
}
foreach (var item in casenumbers)
{
if (!item.Contains("<br />"))
{
txt_referCases.Text += item + Environment.NewLine; // here I'm trying to make all case numbers an individual tags but new line is not making any difference.
}
}
}
.aspx
<asp:TextBox ID="txt_referCases" runat="server"></asp:TextBox>
<script>
$(function () {
var arr = [];
var arrName = [];
$('#<%=txt_referCases.ClientID %>').tagit({
autocomplete: {
delay: 0,
minLength: 3,
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Case.aspx/ReferCases") %>',
data: "{ 'caseNum': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
arr = $.map(data.d, function (el) { return el });
response($.map(data.d, function (item, index) {
return {
label: item,
val: index
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
}
});
});
</script>
Finally solved my own problem. It was just a matter of replacing Environment.NewLine to ',' would do the job. So the line would be
txt_referCases.Text += item + ","
and this will separate the tags.

Circular reference was detected while serializing an object of type

I am trying to fetch company data based on company id through ajax and fill the related textboxes with the received data. Company id is selected through ajax autocomplete. The code was working fine two days back and suddenly it started generating an error for only first two entries of autocomplete and for rest it is working fine. Can anyone point out the mistake in this. Thank you.
Error Details: "Message":"A circular reference was detected while serializing an object of type \u0027System.Data.Entity.DynamicProxies.Company_81625299B5B4D7A3375D55E48BE84921728B8D48335366DF8CA6844A8D10FF5D\u0027.","StackTrace":" at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember)\r\n.
Below is my code:
function setCompanyData(pageurl, txtboxid, txtResultid) {
var temp = true;
var searchTbox = $jq14("[id$=" + txtboxid + "]");
var resultTbox = $jq14("[id$=" + txtResultid + "]");
searchTbox.autocomplete({
source: function (request, response) {
$jq14.ajax({
url: pageurl,
data: "{ 'SearchText': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('*')[0],
val: item.split('*')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
autoSelect: true,
autoFocus: true,
select: function (e, i) {
// e.preventDefault();
searchTbox.val(i.item.label);
resultTbox.val(i.item.val).trigger('change');
temp = true;
// return false;
},
change: function (e, i) {
var cId = resultTbox.val();
if (isEmptyOrSpaces(cId)) {
// error
cId = 0;
searchTbox.val("").trigger('');
}
if (isEmptyOrSpaces(searchTbox.val())) {
// error
cId = 0;
resultTbox.val("").trigger('change');
}
getCompanyDetails(cId);
},
minLength: 0
}).focus(function () {
if (temp) {
$jq14(this).autocomplete("search", "");
temp = false;
}
});
searchTbox.autocomplete("widget").addClass("fixedHeight");}
function getCompanyDetails(cid) {
$jq14.ajax({
url: "/sw/adm/update-delete-company.aspx/GetCompanyData",
data: "{ 'cId': '" + cid + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
beforeSend: function () {
$('#loader').show();
},
complete: function () {
$('#loader').hide();
$("#messageBox").hide().slideDown();
setTimeout(function () {
$("#messageBox").fadeOut();
}, 5000);
},
success: function (result) {
$jq14('#cphMainLeft_txtAddress').val(result.d.CompanyAddress);
$jq14('#cphMainLeft_txtCountry').val(result.d.CompanyCountry);
$jq14('#cphMainLeft_txtCity').val(result.d.CompanyCity);
$jq14('#cphMainLeft_txtNewCompanyName').val(result.d.CompanyName);
$jq14('#cphMainLeft_txtEmail').val(result.d.CompanyEmail);
$jq14('#cphMainLeft_txtPanNo').val(result.d.CompanyPAN);
$jq14('#cphMainLeft_txtTinNo').val(result.d.CompanyTIN);
$jq14('#cphMainLeft_txtPhone').val(result.d.CompanyPhone);
$jq14('#cphMainLeft_txtPincode').val(result.d.CompanyPincode);
$jq14('#cphMainLeft_hfTxtCountry').val(result.d.CompanyCountry);
$jq14("#cphMainLeft_ddlCompanyType").val(result.d.CompanyType);
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
}
C# Webmethod goes like:
[WebMethod]
public static Company GetCompanyData(int cId)
{
Entities db = new Entities();
var companyRecord = (from cmp in db.Companies
where cmp.CompanyId == cId
select cmp).SingleOrDefault();
if (companyRecord != null)
return companyRecord;
else
return new Company();
}
Thank you Ashokkumar M. Prajapati for providing the hint.
Instead of returning Company object from [WebMethod], I have converted the company object to Json string in code behind and returned it.
Here is my WebMethod:
[WebMethod]
public static string GetCompanyData(int cId)
{
Entities db = new Entities();
var companyRecord = (from cmp in db.Companies
where cmp.CompanyId == cId
select cmp).SingleOrDefault();
if (companyRecord == null)
companyRecord = new Company();
string s = string.Empty;
s = JsonConvert.SerializeObject(companyRecord,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return s;
}
Then I updated the success method of getCompanyDetails(cid) to:
success: function (result) {
res = JSON.parse(result.d);
$jq14('#cphMainLeft_txtAddress').val(res['CompanyAddress']);
$jq14('#cphMainLeft_txtCountry').val(res['CompanyCountry']);
$jq14('#cphMainLeft_txtCity').val(res['CompanyCity']);
$jq14('#cphMainLeft_txtNewCompanyName').val(res['CompanyName']);
$jq14('#cphMainLeft_txtEmail').val(res['CompanyEmail']);
$jq14('#cphMainLeft_txtPanNo').val(res['CompanyPAN']);
$jq14('#cphMainLeft_txtTinNo').val(res['CompanyTIN']);
$jq14('#cphMainLeft_txtPhone').val(res['CompanyPhone']);
$jq14('#cphMainLeft_txtPincode').val(res['CompanyPincode']);
$jq14('#cphMainLeft_hfTxtCountry').val(res['CompanyCountry']);
$jq14("#cphMainLeft_ddlCompanyType").val(res['CompanyType']);
}
and it worked wonderfully. Thanks again.

Auto-complete select multiple tags in asp.net

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

How to bind JSON data to dropdownlist in Asp.net MVC using jQuery

I am trying to bind JSON Data to dropdown list
My Scenario is I want to get data and Bind to dynamic dropdown list,
In Seperate Class, I have used linq to get data like
public SelectList getProjects()
{
IEnumerable<SelectListItem> projectslist = (from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
return new SelectList(projectslist, "Value", "Text", PROJ_ID);
}
In Controller:
ViewBag.ProjectList=(from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
In View:
#for (int i = 0; i <2; i++)
{ {
#Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, (SelectList)ViewBag.ProjectList, "-- Choose a Project --", new { #class = "ddlProjectvalue" })
}
Now, I am trying for like if we have three dropdownlist, we select a list item in first dropdown list should not show in second dropdown list, and in third dropdown list should not show both previous selected list items for that i have writtern script like:
<script>
$(document).ready(function () {
$('.ddlProjectvalue').change(function () {
debugger;
var selectedValue = $(this).val();
if (selectedValue != null && selectedValue != '') {
debugger;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/Employer/GetDDLData?selectedValue="+selectedValue,
data: "{}",
dataType: "Json",
success: function (data) {
// first remove the current options if any
$('.ddlProjectvalue').find('option').remove();
// next iterate thru your object adding each option to the drop down\
$(data).each(function (index, item) { // GETTING ERROR HERE
debugger;
$('.ddlProjectvalue').append($('<option></option>').val(item.Value).html(item.Text));
});
},
error: function ajaxError(response) {
alert(response.status + ' ' + response.statusText);
}
});
}
});
});
</script>
and I am returning JSON Data from Controller:
public ActionResult GetDDLData(string selectedValue)
{
int projectid = Convert.ToInt32(selectedValue);
IEnumerable<SelectListItem> projectslist = (from proj in db.PROJECTs where proj.IS_DELETED == "N" && proj.ID != projectid select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
var result = new SelectList(projectslist, "Value", "Text", tm.PROJ_ID);
return Json(result, JsonRequestBehavior.AllowGet);
}
I have tried, but getting Error like
"Syntax error, Unrecognized Expression"
where I am Doing Wrong , please help me anyone.
This will help you :
$.ajax({
url: "#Url.Action("GetDDLData","Employer")",
data: {selectedValue:selectedValue},
dataType: "json",
type: "GET",
error: function () {
alert(" An error occurred.");
},
success: function (data) {
var optionhtml1 = '<option value="' +
0 + '">' + "--Select State--" + '</option>';
$(".ddlProjectvalue").append(optionhtml1);
$.each(data, function (i) {
var optionhtml = '<option value="' +
data[i].Value + '">' +data[i].Text + '</option>';
$(".ddlProjectvalue").append(optionhtml);
});
}
});
//Controller Code
public ActionResult getAccount()
{
var result = new SelectList(db.Partymsts, "Account", "Account");
return Json(result, JsonRequestBehavior.AllowGet);
}
// js code
$.ajax({
type: "POST",
url: "/NewMaster/getAccount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var optionhtml1 = '<option value="' +
0 + '">' + "--Select State--" + '</option>';
$(".cs3").append(optionhtml1);
$.each(data, function (i) {
var optionhtml = '<option value="' +
data[i].Value + '">' +data[i].Text + '</option>';
$(".cs3").append(optionhtml);
});
}
});
// html code
<select id="cs3" name="cs3" class="cs3 form-control input-small"> </select>
its working !!
If your json is correct the below will work.Put the code in your ajax success
success:function(data){
$('.ddlProjectvalue').empty();
$.each(data,function (index, item) {
$('.ddlProjectvalue').append$('<option>', {
value: item.Value,
text: item.Text
}, '<option/>')
}
);
}
We have done in this way
Dropdown.append($('<option></option>').val(item.col1).text(item.col2));
function GetDropDownData(stateid) {
$.ajax({
type: 'GET',
url: '#Url.Action("getdist","Home")',
data: {stateid:stateid},
dataType: 'json',
success: function(data)
{
$("#districtId").empty();
$("#districtId").append('<option value="">--Select--</option>');
$.each(data, function (id, result) {
$("#districtId").append('<option value"'+result.Value+'">'+result.Text+'</option>');
});
},
failure: function () {
$("#districtId").empty();
$("#districtId").append('<option value="">--Select--</option>');
}
});
}

Categories

Resources