I'm really new to programming and I'm trying to create a website in MVC where there's a list of movies. Rather than having the user scrolling through every movie there is, they can simply click on a drop-down filter and choose a letter.
e.g. the movies are: Armageddon, South Park, Zorro, Zelda.
The dropdown list is dynamic, so you have the option to select movies starting with: A, S or Z.
This part is all working, however, I can't figure out how or why, when the user selects a letter and clicks "filter" the variable isn't populated with the user choice. Also, it obviously doesn't actually filter the results i.e. if user selects "Z", it should only show "Zorro" and "Zelda".
Here is my code for the Controller:
public ActionResult Index(string search, string options, int? page)
{
ViewModel viewModel = new ViewModel();
var v = db.ItemCategories.Include(m => m.Movies);
if (!String.IsNullOrEmpty(search))
{
v = v.Where(p => p.Title.Contains(search));
ViewBag.Search = search;
}
var movies = v.OrderBy(p => p.Title).Select(p => p.Title).Distinct();
//first letter of each movie
IEnumerable<string> fL = movies.AsQueryable().Cast<string>().Select(str => str.Substring(0, 1)).Distinct();
//populating the selectList with first letter of each category
foreach (string f in fL)
{
ViewBag.Category = new SelectList(fL);
}
//Below is the bit of code I'm having most issues with. The rest is working as it should,
//however when the user selects a letter from the drop-down and clicks on "filter", the "options" variable = null.
//I have a feeling it has something to do with the type or something, because it was working up until approximately the time when
//I wrote the code for the fL variable for it to choose first letter of each movie
//(when it was selecting whole movie name, the options variable was populating just fine)
if (!String.IsNullOrEmpty(options))
{
v = v.Where(p => p.Title == options);
viewModel.Category = options;
}
v = v.OrderBy(p => p.Title);
const int PageItems = 10;
int currentPage = (page ?? 1);
viewModel.Catego = v.ToPagedList(currentPage, PageItems);
return View(viewModel);
}
Here is my View code:
@using (Html.BeginForm("Index", "Movies", FormMethod.Get))
{
<label>Filter by category:</label>
@Html.DropDownList("Category", "All")
<input type="submit" value="Filter" />
<input type="hidden" name="Search" id="Search" value="@ViewBag.Search" />
}
Any help would be greatly appreciated! Thank you