I have a autocomplete textbox which filters exactly what I want to search for. But now what I want is,
If user doesn't types anything into the textbox and just clicks the textbox. It should show all the result. Is this possbile ?
Below is my code.
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("#txt712").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Frm_Agreement_Master.aspx/GetAutoCompleteData",
data: "{'username':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
},
focus: function () {
return false;
},
select: function (event, ui) {
var terms = split(this.value);
terms.pop();
terms.push(ui.item.value);
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("#txt712").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();
}
}
Also find the link from where I got the reference.
Reference link
UPDATE
Server side code
[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (OracleConnection ObjPriCon = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString()))
{
using (OracleCommand cmd = new OracleCommand("select distinct survey_area_7_12 FROM xxcus.xxacl_pn_farming_mst WHERE survey_area_7_12 LIKE '%' || :searchtext || '%'", ObjPriCon))
{
ObjPriCon.Open();
cmd.Parameters.AddWithValue(":searchtext", username.ToLower());
OracleDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
result.Add(dr["survey_area_7_12"].ToString());
}
}
return result;
}
}
}
In Server code check if the search string is null or not and trigger the query accorduingly
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
**//check if user name is not null**
if(null != username){
using (SqlCommand cmd = new SqlCommand("select DISTINCT UserName from UserInformation where UserName LIKE '%'+#SearchText+'%'", con))}
else{
using (SqlCommand cmd = new SqlCommand("select UserName from UserInformation, con))}
}
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["UserName"].ToString());
}
You can use "Focus" event to do this.
.focus(function () {
$(this).autocomplete("search");
});
Full code as below.
$("#txt712").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Frm_Agreement_Master.aspx/GetAutoCompleteData",
data: "{'username':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
},
focus: function () {
$(this).autocomplete("search"); //New Code
},
select: function (event, ui) {
var terms = split(this.value);
terms.pop();
terms.push(ui.item.value);
terms.push("");
this.value = terms.join(", ");
return false;
}
});
Related
I have these ViewModels:
public class UserAddRoleListViewModel
{
public String Id { get; set; }
public String Name { get; set; }
}
public class SaveUserNewRoleViewModel
{
[Required]
public String RoleId { get; set; }
public String RoleName { get; set; }
public List<UserAddRoleListViewModel> RoleList { get; set; }
}
How can I pass an array of objects that have a format like this:
var object = {
Id: rowIdItem,
Name: rowItem
};
dataSet.push(object);
to my MVC Controller here:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult VerifyRole(SaveUserNewRoleViewModel Input)
{
IEnumerable<object> errors = null;
if (ModelState.IsValid)
{
if(Input.RoleList[0] != null)
{
foreach (var item in Input.RoleList)
{
if (Input.RoleId == item.Id)
{
ModelState.AddModelError("RoleId", "Role already exists");
errors = AjaxError.Render(this);
return Json(new { success = false, errors });
}
}
return Json(new { success = true });
}
return Json(new { success = true });
}
else
{
errors = AjaxError.Render(this);
return Json(new { success = false, errors });
}
}
So far it seems like its always passing an nothing when I debug it
EDIT:
Just to clarify. I can already pass the item via ajax. It's just that when I debug, RoleList is empty.
This is my ajax function:
$(document).on("submit", "#modal", function (e) {
e.preventDefault();
var selectedText = $("##Html.IdFor(m=>m.RoleId) :selected").text();
var selectedId = $("##Html.IdFor(m=>m.RoleId)").val();
var form_data = $(this).serializeArray();
form_data.push({ name: "RoleList", value: dataSet });
console.log(form_data);
rowIdItem = selectedId;
rowItem = selectedText;
$("#close").trigger("click");
$.ajax({
url: "#Url.Action("VerifyRole", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: form_data,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (result) {
if (result.success) {
rowIdItem = selectedId;
rowItem = selectedText;
$("#close").trigger("click");
return;
}
$.each(result.errors, function (index, item) {
// Get message placeholder
var element = $('[data-valmsg-for="' + item.propertyName + '"]');
element.empty();
// Update message
element.append($('<span></span>').text(item.errorMessage));
// Update class names
element.removeClass('field-validation-valid').addClass('field-validation-error');
$('#' + item.propertyName).removeClass('valid').addClass('input-validation-error');
});
}
});
return false;
});
EDIT 2:
Added code that fills dataSet:
$(document).on($.modal.AFTER_CLOSE, function (event, modal) {
dataSet.push(object);
table.row.add(object).draw();
$("#modal").empty();
});
Javascript
$("#myBtn").click(function () {
var dataSet= [];
var obj = {
Id: rowIdItem,
Name: rowItem
};
dataSet.push(obj);
var data = {
"RoleId": '1',
"RoleName ": 'roleName',
"RoleList": dataSet
};
$.ajax({
type: "POST",
traditional:true,
url: "controller/VerifyRole",
content: "application/json;",
dataType: "json",
data: data ,
success: function () {
}
});
});
Controller/Action
[HttpPost]
public ActionResult VerifyRole(SaveUserNewRoleViewModel input)
{
...
}
Try this:)
$(document).on("submit", "#modal", function (e) {
e.preventDefault();
var selectedText = $("##Html.IdFor(m=>m.RoleId) :selected").text();
var selectedId = $("##Html.IdFor(m=>m.RoleId)").val();
var form_data = {};
form_data.RoleId = selectedId;
form_data.RoleName =selectedText;
console.log(form_data);
rowIdItem = selectedId;
rowItem = selectedText;
$("#close").trigger("click");
$.ajax({
url: "#Url.Action("VerifyRole", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: JSON.stringify(form_data),
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (result) {
if (result.success) {
rowIdItem = selectedId;
rowItem = selectedText;
$("#close").trigger("click");
return;
}
$.each(result.errors, function (index, item) {
// Get message placeholder
var element = $('[data-valmsg-for="' + item.propertyName + '"]');
element.empty();
// Update message
element.append($('<span></span>').text(item.errorMessage));
// Update class names
element.removeClass('field-validation-valid').addClass('field-validation-error');
$('#' + item.propertyName).removeClass('valid').addClass('input-validation-error');
});
}
});
return false;
});
my example with datasets:
$("body").on("click", "#btnSave", function () {
var ops = new Array();
$("#table TBODY TR").each(function () {
var row = $(this);
var ps = {};
ps.colname1 = row.find("TD").eq(0).html();
ps.colname2 = row.find("TD").eq(1).html();
ps.colname3= row.find("TD").eq(2).html();
ops.push(ps);
});
var item = {};
item.nam1 = "test";
item.List = ops;
$.ajax({
type: "POST",
url: " ...",
data: JSON.stringify(item),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
}
});
});
I m working on simple registration i have two forms one is registration another is city, When city is newly added it get added update perfectly but when i use city in registration form eg pune. pune will not get edited or updated, code written in ajax
function UpdateCity(Ids) {
debugger;
var Id = { Id: Ids }
$('#UpdateModel').modal('show');
$.ajax({
type: 'GET',
url: "/City/GetCityDetail",
data: Id,
dataType: "json",
success: function (city) {
$('#EditCityName').val(city.CityName);
$('#EditCityId').val(city.CityId);
}
})
$('#UpdateCityButton').click(function () {
var model = {
CityName: $('#EditCityName').val(),
CityId: $('#EditCityId').val()
}
debugger;
$.ajax({
type: 'POST',
url: "/City/UpdateCity",
data: model,
dataType: "text",
success: function (city) {
$('#UpdateModel').modal('hide');
bootbox.alert("City updated");
window.setTimeout(function () { location.reload() }, 3000)
}
})
})
}
Controller
public bool UpdateCity(City model, long CurrentUserId)
{
try
{
var city = db.Cities.Where(x => x.CityId == model.CityId && x.IsActive == true).FirstOrDefault();
if (city == null) return false;
city.CityName = model.CityName;
city.UpdateBy = CurrentUserId;
city.UpdateOn = DateTime.UtcNow;
db.SaveChanges();
return true;
}
catch (Exception Ex)
{
return false;
}
}
A few stabs in the dark here but, try changing your code to the following (with comments).
Controller:
// !! This is a POST transaction from ajax
[HttpPost]
// !! This should return something to ajax call
public JsonResult UpdateCity(City model, long CurrentUserId)
{
try
{
var city = db.Cities.Where(x => x.CityId == model.CityId && x.IsActive == true).FirstOrDefault();
if (city == null) return false;
city.CityName = model.CityName;
city.UpdateBy = CurrentUserId;
city.UpdateOn = DateTime.UtcNow;
db.SaveChanges();
// !! Change return type to Json
return Json(true);
}
catch (Exception Ex)
{
// !! Change return type to Json
return Json(false);
}
}
Script:
function UpdateCity(Ids) {
//debugger;
var Id = { Id: Ids };
$('#UpdateModel').modal('show');
$.ajax({
type: 'GET',
url: "/City/GetCityDetail",
data: Id,
dataType: "json",
success: function (city) {
$('#EditCityName').val(city.CityName);
$('#EditCityId').val(city.CityId);
},
error: function () {
// !! Change this to something more suitable
alert("Error: /City/GetCityDetail");
}
});
$('#UpdateCityButton').click(function () {
var model = {
CityName: $('#EditCityName').val(),
CityId: $('#EditCityId').val()
};
//debugger;
$.ajax({
type: 'POST',
url: "/City/UpdateCity",
data: model,
// !! Change return type to Json (return type from Server)
dataType: "json",
success: function (city) {
// !! Check result from server
if (city) {
$('#UpdateModel').modal('hide');
bootbox.alert("City updated");
// !! Why reload location?
// window.setTimeout(function () { location.reload(); }, 3000);
} else{
// !! Change this to something more suitable
alert("Server Error: /City/UpdateCity");
}
},
error: function () {
// !! Change this to something more suitable
alert("Error: /City/UpdateCity");
}
});
});
}
This should give you some more clues as to what's going on.
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 have an $.ajax function on my page to populate a facility dropdownlist based on a service type selection. If I change my service type selection back and forth between two options, randomly the values in the facility dropdownlist will remain the same and not change. Is there a way to prevent this? Am I doing something wrong?
Javascript
function hydrateFacilityDropDownList() {
var hiddenserviceTypeID = document.getElementById('<%=serviceTypeID.ClientID%>');
var clientContractID = document.getElementById('<%=clientContractID.ClientID%>').value;
var serviceDate = document.getElementById('<%=selectedServiceDate.ClientID%>').value;
var tableName = "resultTable";
$.ajax({
type: 'POST',
beforeSend: function () {
},
url: '<%= ResolveUrl("AddEditService.aspx/HydrateFacilityDropDownList") %>',
data: JSON.stringify({ serviceTypeID: TryParseInt(hiddenserviceTypeID.value, 0), clientContractID: TryParseInt(clientContractID, 0), serviceDate: serviceDate, tableName: tableName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
a(data);
}
,error: function () {
alert('HydrateFacilityDropDownList error');
}
, complete: function () {
}
});
}
function a(data) {
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
var tableName = "resultTable";
if (facilityDropDownList.value != "") {
selectedFacilityID = facilityDropDownList.value;
}
$(facilityDropDownList).empty();
$(facilityDropDownList).prepend($('<option />', { value: "", text: "", selected: "selected" }));
$(data.d).find(tableName).each(function () {
var OptionValue = $(this).find('OptionValue').text();
var OptionText = $(this).find('OptionText').text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
$(facilityDropDownList).append(option);
});
if ($(facilityDropDownList)[0].options.length > 1) {
if ($(facilityDropDownList)[0].options[1].text == "In Home") {
$(facilityDropDownList)[0].selectedIndex = 1;
}
}
if (TryParseInt(selectedFacilityID, 0) > 0) {
$(facilityDropDownList)[0].value = selectedFacilityID;
}
facilityDropDownList_OnChange();
}
Code Behind
[WebMethod]
public static string HydrateFacilityDropDownList(int serviceTypeID, int clientContractID, DateTime serviceDate, string tableName)
{
List<PackageAndServiceItemContent> svcItems = ServiceItemContents;
List<Facility> facilities = Facility.GetAllFacilities().ToList();
if (svcItems != null)
{
// Filter results
if (svcItems.Any(si => si.RequireFacilitySelection))
{
facilities = facilities.Where(f => f.FacilityTypeID > 0).ToList();
}
else
{
facilities = facilities.Where(f => f.FacilityTypeID == 0).ToList();
}
if (serviceTypeID == 0)
{
facilities.Clear();
}
}
return ConvertToXMLForDropDownList(tableName, facilities);
}
public static string ConvertToXMLForDropDownList<T>(string tableName, T genList)
{
// Create dummy table
DataTable dt = new DataTable(tableName);
dt.Columns.Add("OptionValue");
dt.Columns.Add("OptionText");
// Hydrate dummy table with filtered results
if (genList is List<Facility>)
{
foreach (Facility facility in genList as List<Facility>)
{
dt.Rows.Add(Convert.ToString(facility.ID), facility.FacilityName);
}
}
if (genList is List<EmployeeIDAndName>)
{
foreach (EmployeeIDAndName employeeIdAndName in genList as List<EmployeeIDAndName>)
{
dt.Rows.Add(Convert.ToString(employeeIdAndName.EmployeeID), employeeIdAndName.EmployeeName);
}
}
// Convert results to string to be parsed in jquery
string result;
using (StringWriter sw = new StringWriter())
{
dt.WriteXml(sw);
result = sw.ToString();
}
return result;
}
$get return XHR object not the return value of the success call and $get function isn't synchronous so you should wait for success and check data returned from the call
these two lines do something different than what you expect
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
change to something similar to this
var facilityDropDownList;
$.ajax({
url: '<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>',
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
facilityDropDownList= data;
}
});
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
}
}))
}