Pages

Tuesday 11 March 2014

Autocomplete Dropdown depending on textbox text



        When user start typing the character into the TextBox the Dropdownlist will be get filled by the items that starts with the entered text. In follwing code I was showing how to display movie name that starts with entered character into the textbox. But two film may have same name so to differentiate that I also took the star cast of the film and displayed it in the form "MovieName[comma separated star cast] ".

Initial View before entering anything


when user start typing movie Name following output come



/*Ajax call which fill Drop-down list with the movies whose name start with the characters entered in the TextBox*/
$('#filmName').autocomplete({
source: function (request, response) {
$.ajax({
url:'@Url.Action("GetMovies","Agreement")',
data: { query: request.term },
dataType: 'json',
type: 'GET',
async: false,
success: function (movies) {
$("#selectMovie").empty();
for (var i = 0; i < 1; i++) {
for (var j = 0; j < movies[i].Id.length; j++) {
$("#selectMovie").append("<option value=" + movies[i].Id[j] + ">" + movies[i].name[j] + "</option>");
}
}
}
})
},
minLength: 1
});
/*Controller action which retrive moviesName with comma separated StarCast and Id of movie */
/*Ajax call to Get movies to show into dropdown list depending on textbox value for EditAppend*/
public JsonResult GetMovies(string query)
{
AMSEntities db = new AMSEntities();
List<AMSProgram> pgm;
pgm = db.AMSPrograms.Where(x => x.ProgramName.StartsWith(query)).ToList();
var movies = new List<string>();
var moviesId = new List<long>();
int starId;
foreach (var program in pgm)
{
long pgmId = program.ProgramId;
string pgmName = program.ProgramName;
string filmCrew = context.AMSPrograms.Where(x => x.ProgramId == pgmId).Select(y => y.StarCasts).FirstOrDefault();
string starcast = filmCrew.ToString();
string[] actors = starcast.Split(',');
string allActors = pgmName + "[";
for (int i = 0; i < actors.Length - 1; i++)
{
if (actors[i] != "")
{
starId = Convert.ToInt32(actors[i]);
string actorName = context.AMSFilmStars.Where(x => x.FilmStarId == starId).Select(y => y.Name).FirstOrDefault().ToString();
allActors += actorName + ",";
}
}
allActors = allActors + "]";
movies.Add(allActors);
moviesId.Add(pgmId);
}
var result = (from x in pgm select new { name = movies, Id = moviesId });
return Json(result, JsonRequestBehavior.AllowGet);
}

No comments:

Post a Comment