I am trying to
1) create a JQuery AutoComplete box that is populated from an aspx method, and
2)once I get the results, I wish to populate these results inside a list.
At the moment I am trying to do step one however without my success.
My code is as follows:-
ASPX
<script>
$(function () {
$("#persons").autocomplete({
//source: availableTags
source: function (request, response) {
var term = request.term;
var personArray = new Array();
$.post('JQAutoComplete.aspx/FetchPersonList', { personName: term }, function (persons) {
personArray = persons;
alert('PersonArray' - personArray);
alert('Persons' - persons);
response(personArray);
});
}
});
});
<div class="ui-widget">
<label for="persons">Persons: </label>
<input id="persons" />
</div>
</body>
and my aspx.cs is as follows :-
public JsonResult FetchPersonList(string personName)
{
var persons = ctx.GetDataFromXML(false, 0);
return (persons) as JsonResult;
}
*************UPDATE ASPX.CS*******************
ok so I changed the method to this:-
[WebMethod]
public static List<Person> FetchPersonList()
{
//var persons = this.HouseService.SelectByName(houseName).Select(e => new String(e.Name.ToCharArray())).ToArray();
var persons = ctx.GetDataFromXML(false, 0);
return (List<Person>) persons;
}
but I am still not getting through the method!
However the code is not hitting this method at all.
How can I get this list?
Thanks for your help and time
Ok I found the problem.
I changed my JQuery to the following and its calling the method now :-
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("#persons").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "JQAutoComplete2.aspx/FetchPersons",
data: "{'name':'" + document.getElementById('persons').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
alert(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
and my ASPX.CS looks like this :-
[WebMethod]
public static List<Person> FetchPersons(string name)
{
var persons = ctx.GetDataFromXML(false, 0);
return (List<Person>)persons;
}
Related
I am using an ASP.NET MVC web site written in C#. I have code for an autocomplete that works fine in a regular view but not in a partial view. In the partial view,the results are sent back from the controller and the data is there but it is not displayed for the text box in the partial view.
The following is the Javascript code:
$(document).ready(function () {
$("#SearchBox1").autocomplete({
source: function (request, response) {
//alert(request.term);
$.ajax({
url: "/MArrangement/EventDetailAutoView",
type: "POST",
dataType: "json",
async: false,
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
//alert(item.CityName);
return { label: item.CityName, value: item.CityId };
}))
}
})
},
error: function (response) {
alert('1a');
alert(response.responseText);
},
failure: function (response) {
alert('2b');
alert(response.responseText);
},
messages: {
noResults: "", results: ""
}
});
});
This is the partial view:
<div>
<label>Search by Item or Inventory Type</label><br />
#Html.EditorFor(m => m.City.CityName, new { htmlAttributes = new { id = "SearchBox1", style = "position:absolute; z-index:11" } })
</div>
This is the controller code:
[HttpPost]
public JsonResult EventDetailAutoView(string Prefix)
{
List<Models.City> ObjList = new List<City>();
Models.Mod.InventoryMain.getInventory(ref ObjList, Guid.Parse(Session["UserID"].ToString()));
var CityList = (from N in ObjList
where N.CityName.ToLower().Contains(Prefix.ToLower())
select new { N.CityName, N.CityId }).ToList();
return Json(CityList, JsonRequestBehavior.AllowGet);
}
The method EventDetailAutoView is being called and is returning the correct data. In the success portion of the Javascript code, the data is shown (I put in a alert statement to see the data) but the results are not displayed underneath the SearchBox1 text box. The following code works fine in a regular view but not in a partial view.
You should add same code in regular view once partial view loads successfully.
var strUrDomainNamel = + '/Controller/Method';
$.ajax({
url: strUrl,
cache: false,
data: {},
type: 'POST',
success: function (data) {
$(".partialLoadview").html(data);
$("#SearchBox1").autocomplete({
//Your code for autocomplete must be here.
});
},
error: function (req, status, error) {
alert('error message');
}
});
EDIT: The below code works, for anybody who would need!
This question is asked alot but couldn't find help for this specific one. I need to show a dropdown list that loads while I type in a search bar. While I type, I need to search in Active Directory for the Username that is being typed, and then it shows in the dropdown list all the options (say, it would only show results after 4 characters).
I have a simple form with one input, one button, a controller function to search user from a C# class that allows me to acces the AD. I put the JQuery script which retrieves data. The data is being correctly fetched but I cannot show it in the autocomplete. Any ideas?
The form:
<form class="form-inline" method="post" action="~/Home/SearchUserResult">
<label class="sr-only" for="inlineFormInput"> Nom et/ou Prénom </label>
<input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0" name="searchName" id="searchName" placeholder="Nom et/ou prénom"/>
<button class="btn btn-primary" type="submit" id="searchValidate"> Rechercher </button>
</form>
My AD search function:
public List<string> SearchUserByName(string name)
{
try
{
SearchResultCollection resultCollection;
DirectoryEntry ldapConnection = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(ldapConnection);
search.Filter = "(anr=" + name + ")";
search.PropertiesToLoad.Add("displayName");
resultCollection = search.FindAll();
if (resultCollection.Count == 0)
{
return null;
}
else
{
foreach(SearchResult sResult in resultCollection)
{
lastName.Add(sResult.Properties["displayName"][0].ToString());
}
}
return lastName;
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
return null;
}
}
Here is the Controller function suggest by #caner
public ActionResult SearchUserByName(string name)
{
ADManager adManager = new ADManager();
List<string> lastName = adManager.SearchUserByName(name);
if (lastName != null)
{
ViewData["Names"] = lastName;
return Json(lastName,JsonRequestBehavior.AllowGet);
}
return null;
}
Finally here is the script I have for now, it gets the data but does not show it (in alert(data) I retrieve all the info I need):
<script>
$(function () {
$("#searchName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/SearchUserByName",
type: "GET",
data: { name: $("#searchName").val() },
contentType: "application/json;charset=utf-8",
dataType: "JSON",
success: function (data) {
alert(data)
response($.map(data, function (item) {
return {
label: item
}
}));
},
});
},
minLength: 4
})
});
</script>
Thanks for your help
EDIT: createDirectoryEntry() is a function I made just to create connection to AD.
EDIT 2 : If you have any other ideas to do that with something else than JQuery, I'm open to everything
Try jquery autocomplete like this...
your script:
$(function () {
$("#searchName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/YourController/SearchUserByName",
type: "POST",
data: { name: $("#searchName").val() },
dataType: "JSON",
success: function (data) {
response($.map(data.lastName, function (item) {
return {
label: item
}
}));
},
});
},
minLength: 4
})
});
and your controller method:
public ActionResult SearchUserByName(string name)
{
.
.
.
return Json(lastName);
}
This script works for me:
<script>
$(function () {
$("#searchName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/SearchUserByName",
type: "GET",
data: { name: $("#searchName").val() },
contentType: "application/json;charset=utf-8",
dataType: "JSON",
success: function (data) {
alert(data)
response($.map(data, function (item) {
return {
label: item
}
}));
},
});
},
minLength: 4
})
});
</script>
So having a bit trouble figuring out how to successfully use AJAX to call a method and retrieve data. I am being asked to do this, not exactly sure why but I would usually just handle all this stuff in a MVC environment in the Controller. But for now I am asked to do this in AJAX. I have a ASPX file that I am simply trying to see work so i can move on. So far none of the stack overflow suggestions helped.
Here's what I currently have:
.ASPX/source
<script type="text/javascript">
$(document).ready(function () {
$("#go").click(function () {
$.ajax({
type: "GET",
url: "Default.aspx/ItemData",
processData: true,
data: {},
dataType: "json",
success: function () { alert("yay") },
error: function () { alert("nay") }
});
});
});
</script>
And then in my Default.aspx.cs file I have a method 'ItemData'
[WebMethod]
public static NextCrew.Models.Item ItemData(string cookieID)
{
Item item = new Item();
item.name = "Fred";
item.idx = 1;
item.completed = 1;
return item;
}
(Item is simple a Model withg 3 properties: Name(string), idx(int) and completed(int) )
I am having a hard time figuring out what I am doing wrong here. Can someone please write an example of what I am trying to do? Just a simple GET request that I can return an object (once I get done testing I want to be able to connect to a DB so I need it to be an object) using AJAX.
I can't tell what I am doing wrong but I have some ideas:
1)maybe my url in the ajax isn't formatted properly?
2)do i need to pass anything into data if I have a parameter?
3)is my get method in the correct .cs file?
UPDATE
I was informed I need to have a special class to handle this. I tried to then make a .asmx and the AJAX is still not being called. Hoping someone sees an error that I missed.
<script>
$(function () {
$.ajax({
type: "POST",
contentType: "application/json",
url: "WebService2.asmx/GetItems",
data: "{}",
dataType: 'Json',
success: function (result) {
// alert(result.d);
$.each(result.d, function (index, ele) {
$("#Myddl").append("<option value='" + ele.value + "'>" + ele.text + "</option>");
})
}
});
})
</script>
.asmx
public class WebService2 : System.Web.Services.WebService
{
[WebMethod]
public List<Item2> GetItems()
{
//suppose data comes from database
var result = new List<Item2>() {
new Item2{ text="one",value="one"},
new Item2{ text="two",value="two"},
new Item2{ text="three",value="three"}
};
return result;
}
public class Item2
{
public string text { get; set; }
public string value { get; set; }
}
}
I have a Jquery Script and whenever a drop-downlist value changes, it is supposed to take the value and pass it into a method that gets the value and calculates a price based on the value and then in the end sets a label to the new value.
Here is my Jquery Script:
#section PageScripts{
<script type="text/javascript">
$(document).ready(function () {
$('#paperTypeJList').change(function () {
// trying to figure out how to pass the value to the following method
});
});
</script>
}
Here is my method that I'm trying to call inside of the Jquery Script:
public decimal getNewPrice(string dropdownValue)
{
// do something with value and return a decimal
return 0;
}
You have to send ajax call using jquery to server.
Something like this:
<script type="text/javascript">
$(document).ready(function () {
$('#paperTypeJList').change(function () {
// trying to figure out how to pass the value to the following method
var value = $(this).val();
$.ajax({
url: '#Url.Action("Action","Controller")',
data: {dropdownValue:value},
cache: false,
success: function(response){
alert(response);
}
});
});
});
</script>
Try this using jquery Ajax
Html :
<label id="priceLabel"></label>
Javascript
$(document).ready(function () {
$('#paperTypeJList').change(function () {
$.ajax({
type: "GET",
url: "/Home/getNewPrice?dropdownValue=" + this.value,
async: true,
success: function (result) {
document.getElementById('priceLabel').innerHTML = result;
}
});
});
});
Controller
public decimal getNewPrice(string dropdownValue)
{
// do something with value and return a decimal
return 5.72M;
}
$(document).ready(function () {
$('#paperTypeJList').change(function () {
getNewPrice($(this).val());
});
});
My current code is below:
#section PageScripts{
<script type="text/javascript">
$(document).ready(function () {
$('#paperTypeJList').change(function () {
$.ajax({
type: "GET",
url: "/Home/getNewPrice?dropdownValue=" + this.value,
async: true,
success: function (result) {
document.getElementById('priceLabel').innerHTML = result;
}
});
});
});
</script>
}
public decimal getNewPrice(string dropdownValue)
{
// do something with value and return a decimal
return 5.72M;
}
//When focusout event is working, tested with alert.. but ajax call is not working and my aspx.cs method also not firing.. Please solve this issue.
//This is my aspx page jquery code.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var elem = document.getElementById('<%=txtProduct.ClientID %>');
$(elem).focusout(function () {
myF($(this).val());
});
function myF(value) {
var fist = value.split(' ( ', 1);
$.ajax({
type: 'POST',
url: 'Invoice.aspx/getProductDetails',
data: "{'strCode':'" + fist + "'}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
alert(response.d.toString());
},
failure: function (response) {
alert('error');
}
});
}
});
</script>
//Server side code
[WebMethod]
public static string getProductDetails(string strCode)
{
List<string> companyInfo = new List<string>();
companyInfo.Add(HttpContext.Current.Cache[Convert.ToString(HttpContext.Current.Session["UserID"]) + "CompanyID"].ToString());
companyInfo.Add(strCode);
List<string> price = Database.MasterDB.getProductInfo(companyInfo);
if (price.Count > 0)
return price[0].ToString();
else
return "000";
}
Since you are using Session thing inside web method, that might be giving null values or blank values. This is because you have not enabled session for webmethod.
Like this - [WebMethod(EnableSession=true)].
Read more