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');
}
});
Related
I have the following jquery function which is sending data to a controller:
function bound(e) {
var ele = document.getElementsByClassName("e-grid")[0]
ele.addEventListener('click', function (e) {
if (e.target.classList.contains('e-up')) {
var grid = document.getElementById('FlatGrid').ej2_instances[0]; //Grid Instance
var rowObj = grid.getRowObjectFromUID(ej.base.closest(e.target, '.e-row').getAttribute('data-uid'));
var data = rowObj.data;
//alert(JSON.stringify(data));
var code = data.ClientCode;
$.ajax({
type: "POST",
url: "/Client/ShowClient",
data: { "ClientCode": code }, //First item has latest ID
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
}
});
}
And my controller method:
[HttpPost]
public ActionResult ShowClient(string ClientCode)
{
if (ClientCode == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
*action*
}
However I am getting a 500 (Internal Server Error) error for this. Any idea what I am missing cause my method is not being hit at all.
And I can see that var code does have the correct string value.
Remove commas from the parameter name "ClientCode" and contentType and will be work
$.ajax({
type: "POST",
url: "/Client/ShowClient",
data: { ClientCode: code }, //First item has latest ID
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
The comments have provided you with a combination of suggestions that when put together will give you the desired behavior.
First, you can build the URL in teh view using #Url.Action
url: '#(Url.Action("ShowClient","Client"))',
Next, the object model is not being built correctly
data: { ClientCode: code },
Note the last of quotes around the key.
And finally remove the JSON content type.
Which results to portion of code.
$.ajax({
type: "POST",
url: '#(Url.Action("ShowClient","Client"))',
data: { ClientCode: code },
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
Change the url to this:
url: "../Client/ShowClient"
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>
I am using ASP.NET MVC3 with EF Code First. I have not worked previously with jQuery. I would like to add autocomplete capability to a dropdownlist that is bound to my model. The dropdownlist stores the ID, and displays the value.
So, how do I wire up the jQuery UI auto complete widget to display the value as the user is typing but store the ID?
I will need multiple auto complete dropdowns in one view too.
I saw this plugin: http://harvesthq.github.com/chosen/ but I am not sure I want to add more "stuff" to my project. Is there a way to do this with jQuery UI?
Update
I just posted a sample project showcasing the jQueryUI autocomplete on a textbox at GitHub
https://github.com/alfalfastrange/jQueryAutocompleteSample
I use it with regular MVC TextBox like
#Html.TextBoxFor(model => model.MainBranch, new {id = "SearchField", #class = "ui-widget TextField_220" })
Here's a clip of my Ajax call
It initially checks its internal cached for the item being searched for, if not found it fires off the Ajax request to my controller action to retrieve matching records
$("#SearchField").autocomplete({
source: function (request, response) {
var term = request.term;
if (term in entityCache) {
response(entityCache[term]);
return;
}
if (entitiesXhr != null) {
entitiesXhr.abort();
}
$.ajax({
url: actionUrl,
data: request,
type: "GET",
contentType: "application/json; charset=utf-8",
timeout: 10000,
dataType: "json",
success: function (data) {
entityCache[term] = term;
response($.map(data, function (item) {
return { label: item.SchoolName, value: item.EntityName, id: item.EntityID, code: item.EntityCode };
}));
}
});
},
minLength: 3,
select: function (event, result) {
var id = result.item.id;
var code = result.item.code;
getEntityXhr(id, code);
}
});
This isn't all the code but you should be able to see here how the cache is search, and then the Ajax call is made, and then what is done with the response. I have a select section so I can do something with the selected value
This is what I did FWIW.
$(document).ready(function () {
$('#CustomerByName').autocomplete(
{
source: function (request, response) {
$.ajax(
{
url: "/Cases/FindByName", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.CustomerName,
value: item.CustomerName,
id: item.CustomerID
}
})
);
},
});
},
select: function (event, ui) {
$('#CustomerID').val(ui.item.id);
},
minLength: 1
});
});
Works great!
I have seen this issue many times. You can see some of my code that works this out at cascading dropdown loses select items after post
also this link maybe helpful - http://geekswithblogs.net/ranganh/archive/2011/06/14/cascading-dropdownlist-in-asp.net-mvc-3-using-jquery.aspx
I have two dropdownlists for Languages and Countries
On selecting a language in the dropdownlist, should fill corresponding countries in the country dropdownlist
#Html.DropDownList("LanguageSelectList", null, null, new { #class = "hyper-select fixedwidth300"})
#Html.DropDownList("CountrySelectList", null, null, new { #class = "hyper-select fixedwidth300" })
Here is my jquery script
$("#LanguageSelectList").change(function (event) {
$("#languageValidator").hide();
var selectedLanguage = $("#LanguageSelectList").val();
debugger;
//--------
if (selectedLanguage!='') {
var url = '#Url.Action("GetCountryListByLanguage", "Options")';
$.ajax({
type: "POST",
url: url,
data: { selectedLanguage: selectedLanguage },
dataType: "json",
contentType: "application/json; charset=utf-8",
global: false,
async: false,
success: function (data) {
var ddlCountrylist = $("#CountrySelectList");
debugger;
var jsonString =JSON.stringify(data);
//here how to take data from jsonstring to countries dropdownlist
}
});
} else {
alert('no country returnned');
}
//--------------
});
I am able to retrieve the expected list of countries in the json data as given below .Now how do I fill my country dropdownlist.
jsonString="[{\"Selected\":false,\"Text\":\"n/a\",\"Value\":\"\"},{\"Selected\":false,\"Text\":\"China\",\"Value\":\"CN\"},{\"Selected\":false,\"Text\":\"Hong Kong\",\"Value\":\"HK\"},{\"Selected\":false,\"Text\":\"Singapore\",\"Value\":\"SG\"},{\"Selected\":false,\"Text\":\"Taiwan\",\"Value\":\"TW\"}]"
In the success section of your ajax call to the controller method, you can write the below code:
success: function (data) {
$('#CountrySelectList').empty();
$.each(data.agent, function() {
$('#CountrySelectList').append(
$('<option/>', {
value: this.Value,
html: this.Text
})
);
});
}
I have not tested the above code, but I hope this would definitely work
inside your success handler just iterate thru the returned array and add an option to drop down list for each element in the array.
ddlCountrylist.find('option').remove();
$(data).each(function(i,v){
$('<option value='+v.Value+'>'+v.Text+'</option>').appendTo(ddlCountrylist);
});
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;
}