MVC ASP Autocomplete - javascript

I know there are a few posts on this matter, but I couldn't get any option working. I'm going nuts.
I'm pretty new in MVC and JavaScript. I get the following error in my console:
FamilyStudentJS.js:20 Uncaught TypeError: $(...).autocomplete is not a function
at HTMLDocument. (FamilyStudentJS.js:20)
at fire (jquery-1.12.4.js:3232)
at Object.fireWith [as resolveWith] (jquery-1.12.4.js:3362)
at Function.ready (jquery-1.12.4.js:3582)
at HTMLDocument.completed (jquery-1.12.4.js:3617)
I tried many references. Still, my C# function isn't launched. When I manually run it, it works fine.
My HTML code:
<div class="form-group">
#Html.LabelFor(model => model.FamilyNum, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10" id="fs">
<label> <input type="checkbox" id="FamilyCheckBox"> Family attached? </label>
<div id="familysection" style="display:none" >
<span>
<input type="text" id="FamilyIDTextBox" />
</span>
</div>
#Html.ValidationMessageFor(model => model.FamilyNum, "", new { #class = "text-danger" })
</div>
</div>
JavaScript:
$(document).ready(function () {
$("#FamilyCheckBox").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Students/GetSearchValue",
type: "POST", dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.startfrom };
}));
}
});
},
messages: { noResults: "", results: "" }
});
})
C#:
public JsonResult GetSearchValue(string search)
{
var temp = new FamilyViewModel();
EzappContext db = new EzappContext();
List<Family> allsearch = db.Families.Where(x => x.FamilyName.Contains(search)).Select(x => new Family
{
FamilyName = x.FamilyName,
FamilyNum = x.FamilyNum
}).ToList();
return new JsonResult { Data = allsearch, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

Related

Dynamic DropDownList in ASP.NET MVC NO ACTION RESULT CREATE()

I CANNOT CREATE CASCADING DROPDOWN IN ACTIONRESULT CREATE, ONLY IN ACTION RESULT INDEX IT WORKS
THERE GOES THE CODE
CONTROLLER
public class PessoasController : Controller
{
private GestarkContext db = new GestarkContext();
// GET: Pessoas
public ActionResult Index()
{
ViewBag.Gabinetes = new SelectList(db.Gabinetes, "GabineteId", "Nome");
var pessoageral = db.Pessoas.Include(a => a.gabojecto).Include(a => a.nivelojecto);
return View(pessoageral.ToList());
}
[HttpPost]
public JsonResult getDistricts(int gbtID)
{
List<Departamento> DepartamentoList = db.Departamentoes.Where(p => p.GbtId == gbtID).ToList();
return Json(DepartamentoList, JsonRequestBehavior.AllowGet);
}
VIEW INDEX - IT WORKS HERE
<script>
$(function () {
$('#Gabinetes').change(function () {
var gbtID = $(this).val();
$.ajax({
type: "post",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "getDistricts",
data: "{gbtID:'" + gbtID + "'}",
success: function (data) {
$('#DepartamentoList').empty();
$('#DepartamentoList').append('<option selected="selected" value="">Select Departamento</option>')
$.each(data, function (i, d) {
$('#DepartamentoList').append('<option value=' + d.DircId + '>' + d.Depto + '</option>');
});
},
failure: function (data) {
alert('error occured');
}
});
});
});
</script>
<h2>Lista de Funcioários Registrados</h2>
<br />
<label class="col-md-2 control-label">Gabinete</label>
<div class="col-md-5">
#Html.DropDownList("Gabinetes", null, htmlAttributes: new { #class = "form-control" })
</div>
<div class="form-group">
<label class="col-md-2 control-label">Departamento</label>
<div class="col-md-4">
<select id="DepartamentoList" name="DepartamentoList" class="form-control"></select>
</div>
</div>
<p>
#Html.ActionLink("Visualizar Formulário", "Index", "Principal", null, new { #class = "btn btn-default" }) | #Html.ActionLink("Adicionar Novo", "Create", null, new { #class = "btn btn-primary" }) | #Html.ActionLink("Exportar em Excel", "ExportToExcel", null, new { #class = "btn btn-success" })
</p>
...........
NOW ON VIEW CREATE DOES NOT WORK
I write the code as I do in index, but it doesn't work
I NEED YOUR HELP PLEASE

How can I get my jquery autocomplete to fill in multiple fields in MVC?

I am trying to setup an autocomplete in jquery that gets information from a user in Active Directory. A user can type in a few letters of a person's last name, and what returns is a 2D list (List>) that contains all the people whose last name starts with those letters. Each List holds the first, middle, last name and AD name of a person. And of course, each List> element represents a person.
I have no issues getting the data in jquery. The problem is that I can't seem to figure out how to make it populate the Employee_Name and Employee_Name_AD fields with the information in this array once the user clicks on a name from the list. This is my jquery code:
#section page {
<script type="text/javascript">
$(document).ready(function () {
var name;
var adname;
$("#TESTING").autocomplete(
{
source: function (request, response) {
$.ajax({
url: "/Employees/GetUserList",
type: "POST",
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
name = item[0] + " " + item[1] + " " + item[2];
adname = item[3];
return { label: name, data: [name, adname] };
}))
},
select: function (event, ui) {
$('#Employee_Name').val(ui.data.item.data[0]);
$('#Employee_Name_AD').val(ui.data.item.data[1]);
}
})
},
});
})
</script>
}
And on the same page, here is the accommodating Razor code:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-10">
#Html.TextBox("TESTING")
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee_Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee_Name_AD, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_Name_AD, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_Name_AD, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
I found something super close to what I want thanks to stack overflow: http://jsbin.com/vasuliru/2/edit?html,js,output
The problem with the previous example is that the data is declared on the page itself, not pulled from a data source. How can I modify my code to get it to do what I want?
I was finally about to find a solution, after I came across something in php: Jquery ui autocomplete on multiple input fields with ajax results.
My final code is this:
#section page {
<script type="text/javascript">
$(document).ready(function () {
var name;
var adname;
$("#UserLookup").autocomplete(
{
source: function (request, response) {
$.ajax({
url: "/Employees/GetUserList",
type: "POST",
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
name = item[0] + " " + item[1] + " " + item[2];
adname = item[3];
console.log(adname);
return { label: name, data: item }
}));
}
});
},
select: function (event, ui) {
console.log(ui.item);
$(this).val(ui.item.label);
var userid = ui.item.value;
console.log("Here is the userid:");
console.log(item);
console.log(ui.item.data[3]);
$('#Employee_Name').val(ui.item.value);
$('#Employee_Name_AD').val(ui.item.data[3]);
}
});
});
</script>
}

Jquery Ajax call does not call Asp.net mvc controller action method

I have two drop-downs State and City.According to State selected city should be loaded.So I use State drop-down change event to call ajax method to populate City drop-down.
HTML
<div class="row">
<div class="col-sm-6 ">
<div class="form-group">
<label>State</label>
#Html.DropDownListFor(m => m.State, Model.States, "Please select a State", new { #class = "form-control" })
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6 ">
<div class="form-group">
<label>Cities</label>
#Html.DropDownListFor(m => m.CityRegisterScreen, new SelectList(string.Empty, "Id", "Name"), "Please select a city", new { #class = "form-control" })
</div>
</div>
</div>
JavaScript
This Contains Jquery and Javascript Code.
$(document).ready(function () {
$("#State").on("change", function () { // whenever a selection is made
$("#CityRegisterScreen").empty();
var id = $("#State").val();
$.ajax({
type: 'GET', // we are calling json method
url: '#Url.Action("GetCitiesByDistrict", "Account")',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: { id: id },
success: function (cities) {
$.each(cities, function (i, city) {
$("#CityRegisterScreen").append('<option value="' + city.value + '">' +
city.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve cities.' + ex);
}
});
return false;
});
});
Controller
This is the controller action method which returns Json
public JsonResult GetCitiesByDistrict(int id)
{
List<SelectListItem> cities = new List<SelectListItem>();
var city = new List<City>();
using (ApplicationDbContext context = new ApplicationDbContext())
{
city = context.Cities.Where(e => e.DistrictId == id).ToList();
}
return Json(new SelectList(city, "Id", "Name"), JsonRequestBehavior.AllowGet);
}
Issue is when ajax method is called it doesn't call the Action method in controller.I double checked the URL and DataType it's all perfect.But Action method didn't get called.
It is silly!!! How did i miss this. Thank You #Rajshekar Reddy for your comment it guided me. I am missing [AllowAnonymous] attribute.
[AllowAnonymous]
public JsonResult GetCitiesByDistrict(int id)
{
List<SelectListItem> cities = new List<SelectListItem>();
var city = new List<City>();
using (ApplicationDbContext context = new ApplicationDbContext())
{
city = context.Cities.Where(e => e.DistrictId == id).ToList();
}
return Json(new SelectList(city, "Id", "Name"), JsonRequestBehavior.AllowGet);
}
This is a code for loading States according to selected country. Try this solution.
HTML
#Html.DropDownListFor(model => model.CustAddr_Country_ID, Model.Countries, "Select Country", htmlAttributes: new { #class = "disableInput", #id = "ddlstate", #onchange = "javascript:GetCity(this.value);" })
#Html.DropDownListFor(model => model.CustAddr_State_ID, ViewBag.CustAddr_State_ID as SelectList, "Select State", htmlAttributes: new { #class = "disableInput"})
Script
function GetCity(_stateId) {
$("#CustAddr_State_ID").empty().trigger('change');
var newOption = new Option("Select State", 0, true, true);
$("#CustAddr_State_ID").append(newOption).trigger('change');
if (_stateId != null && _stateId != "") {
var url = "/Ajax/GetCityByStaeId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
for (var x = 0; x < data.length; x++) {
var newOption = new Option(data[x].Text, data[x].Value, true, true);
$("#CustAddr_State_ID").append(newOption).trigger('change');
}
$('#CustAddr_State_ID').val('0').trigger('change');
},
error: function (reponse) {
//alert("error : " + reponse);
}
});
}
}
Controller
[HttpPost]
public ActionResult GetCityByStaeId(int stateid)
{
List<State> objcity = new List<State>();
objcity = _state.GetState().Where(m => m.State_Country_ID == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "State_ID", "State_Name", 0);
return Json(obgcity);
}

Ajax request does not work on a cascading dropdown value change

Hi I have a cascading drop-down and on it's change I have a requirement to populate another field by getting it's value from the database.
unfortunately when I try to populate the drop-down my ajax always responds an error 500. I don't know what is wrong with it.
I am using this tutorial as my guide.
Here is my Javascript
<script>
$(function () {
$('#selectedExperience_ExpertiseID').change(function () {
var selectedExpertise = $('#selectedExperience_ExpertiseID :selected').val();
selectedExpertise = selectedExpertise == "" ? 0 : selectedExpertise;
//When select 'optionLabel' we need to reset it to default as well. So not need
//travel back to server.
if (selectedExpertise == "") {
$('#selectedExperience_FunctionID').empty();
$('#selectedExperience_FunctionID').append('<option value="">--Select a language--</option>');
return;
}
//This is where the dropdownlist cascading main function
$.ajax({
type: "GET",
url: "GetFunctionByID", //Your Action name in the DropDownListConstroller.cs
async: false,
data: { selectedExpertise: selectedExpertise }, //Parameter in this function, Is cast sensitive and also type must be string
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
//When succeed get data from server construct the dropdownlist here.
if (data != null) {
$('#selectedExperience_FunctionID').empty();
$.each(data.function, function (index, data) {
$('#selectedExperience_FunctionID').append('<option value="' + data.Value + '">' + data.Text + '</option>');
});
}
}).fail(function (response) {
if (response.status != 0) {
alert(response.status + " " + response.statusText);
}
});
});
});
</script>
and here is my HTML
<div class="form-group">
#Html.LabelFor(model => model.selectedExperience.ExpertiseID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.selectedExperience.ExpertiseID, Model.expertise, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.selectedExperience.ExpertiseID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.selectedExperience.FunctionID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.selectedExperience.FunctionID, Model.function, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.selectedExperience.FunctionID, "", new { #class = "text-danger" })
</div>
</div>
Please help me. I am stuck in this functionality for 4 days now.
point me to the right direction.
Thanks!
i think your ajax is not sending any data because of this
data: { selectedExpertise: selectedExpertise }
change it to
data: { 'selectedExpertise': selectedExpertise }
i think there should be a quote around the object name
Firstly , give id to both the dropdownlists,I didnt find selectedExperience_ExpertiseID and check the $.each function result
Also,I have modified bit of html. Kindly try this code. Hope your method GetFunctionByID is working well.I have take table and its column according to my reference db.
<script type="text/javascript">
$(function () {
$('#selectedExperience_ExpertiseID').change(function () {
var selectedExpertise = $('#selectedExperience_ExpertiseID :selected').val();
selectedExpertise = selectedExpertise == "" ? 0 : selectedExpertise;
//When select 'optionLabel' we need to reset it to default as well. So not need
//travel back to server.
if (selectedExpertise == "") {
$('#selectedExperience_FunctionID').empty();
$('#selectedExperience_FunctionID').append('<option value="">--Select a language--</option>');
return;
}
//This is where the dropdownlist cascading main function
$.ajax({
type: "GET",
url: "/DropDownList/GetFunctionByID", //Your Action name in the DropDownListConstroller.cs
async: false,
data: { stateId: selectedExpertise }, //Parameter in this function, Is cast sensitive and also type must be string
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
//When succeed get data from server construct the dropdownlist here.
if (data != null) {
$('#selectedExperience_FunctionID').empty();
$.each(data, function (key, val) {
$('#selectedExperience_FunctionID').append('<option value="' + val.value + '">' + val.Text + '</option>');
});
}
}).fail(function (response) {
if (response.status != 0) {
alert(response.status + " " + response.statusText);
}
});
});
});
</script>
#model WebApplication6.Models.StudentModel
#{
ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<div class="form-group">
#Html.Label("Expertise", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StateNames, Model.StateNames, new { #class = "form-control", #id = "selectedExperience_ExpertiseID" })
#Html.ValidationMessageFor(model => model.StateNames, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Function", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.DistrictNames, new List<SelectListItem>(), new { #class = "form-control", #id = "selectedExperience_FunctionID" })
#Html.ValidationMessageFor(model => model.DistrictNames, "", new { #class = "text-danger" })
</div>
</div>

JQuery ui autocomplete in a MVC partial view only works once

I've been trying to get autocomplete to work for my partial view using JQuery ui. The partial view is updated using AJAX.
The problem is that the autocomplete only works up until the point where the partial view is updated.
This is my partial view
<div id="tagList">
#using (Ajax.BeginForm("AddToTagList", new { urlLocation = Model.UrlLocation }, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "tagList" }))
{
if (Model.TagList != null)
{
<div class="form-group">
#Html.LabelFor(model => model.Tag.Text, "Tags", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-xs-10">
<div class="input-group" style="max-width: 300px;">
#Html.EditorFor(model => model.Tag.Text, new { htmlAttributes = new { #class = "form-control", #id = "search_term" } })
#Html.ValidationMessageFor(model => model.Tag.Text, "", new { #class = "text-danger" })
<div class="input-group-btn">
<button type="submit" value="Add Tag" class="btn btn-default">+</button>
</div>
</div>
</div>
</div>
}
}
</div>
This is my JavaScript
$(document).ready(function () {
$("#search_term").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Tag/SearchAutoComplete",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Text, value: item.Text };
}));
}
});
},
});
});
and this is my autocomplete search action
public JsonResult SearchAutoComplete(string term)
{
using (IDocumentSession session = RavenDbConfig.RavenDBDocumentStore.OpenSession())
{
var results = session.Query<Tag>().Where(x => x.Text.StartsWith(term)).ToList();
return Json(results,JsonRequestBehavior.AllowGet);
}
}
So, my question is, how can i make this work even after the partial view has been updated once?
Your problem is when you reload your PartialView you basicaly delete some part of DOM in your html document and create new one. And all your bindings that you add in $(document).ready() event will be lost.
One of the posible solutions for this problem is to place your autocomplete init code in addition to .ready() event in jquery .ajaxSuccess() global event becouse you reload your PartialViews via Ajax. Like this:
$(document).ajaxSuccess(function() {
$("#search_term").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Tag/SearchAutoComplete",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Text, value: item.Text };
}));
}
});
},
});
});
That way you will init your autocomplete every time you reload PartialView.

Categories

Resources