Creating a page to display selected movies based on genre using $.post method.
If no genre is selected, all movies should be displayed as the default selection.
This is the code for the Controller:
public class BrowseController : Controller
{
private MovieContext context = new MovieContext();
// GET: Browse
public ActionResult Index()
{
ViewBag.Genres = context.Genre.ToList();
IEnumerable<Movie> mov = TempData["movies"] as IEnumerable<Movie>;
if (mov == null)
{
IEnumerable<Movie> movies = context.Movies.ToList();
return View(movies);
}
return View(mov);
}
[HttpPost]
public ActionResult Index(int id = -1)
{
IEnumerable<Movie> model;
if (id != -1)
{
model = context.Movies.Where(x => x.GenreId == id);
}
else
{
model = context.Movies.ToList();
}
ViewBag.Genres = context.Genre.ToList();
TempData["movies"] = model;
return RedirectToAction("", "Browse");
}
}
This is the view code:
@model IEnumerable<Movies.Models.Movie>
@using Movies.Models
@{
ViewBag.Title = "Index";
var Movie = Model.FirstOrDefault();
List<Genre> Genres = ViewBag.Genres;
}
@Html.DropDownListFor(m => Movie.GenreId, new SelectList(Genres, "Id",
"Name"), "")
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Rating)
</th>
<th>
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Rating)
</td>
<td></td>
</tr>
}
</table>
@section Scripts{
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$('select#Movie_GenreId').on('change', function () {
var value = $(this).find(':selected').val();
var url = "/Browse/Index";
$.post(url, { id: value });
});
</script>
}
After checking Chrome Debugging tool and Network tab, there are no errors shown in the Preview tab of response. The Get Browse/Index action is returning expected results but not displaying them in the View. I am unsure why this is happening.