0
(I decided to make another post, as advice of another user)
In my Movies view there is a list of all the movies you have in the database and I added um botão, uma caixa de texto e 2 radio buttons(para escolher se quero pesquisar por Nome do filme ou por Categoria do filme)
. In the If
only the Category is specified because the Name is Default first. My goal is to make a search system by Name or Category. After changing the code of If
previous error was solved but a new one related to Model appeared.
Controller:
public ActionResult Index(string searchBy, string search)
{
MovieViewModel[] movies = db.MoviesData.Select(movie => new MovieViewModel
{
MovieID = movie.MovieID,
MovieName = movie.MovieName,
MovieDescription = movie.MovieDescription,
MovieCategory = movie.MovieCategory,
MovieYear = movie.MovieYear
}).ToArray();
if (searchBy == "Categoria")
{
return View(movies.Where(x => x.MovieCategory==search || search == null).ToList());
}
else
{
return View(movies.Where(x => x.MovieName != null && (search == null || x.MovieName.StartsWith(search))).ToList());
}
}
Main View of the Movies:
@model WebApplication3.Models.MovieViewModel[]
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Movies</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<p>
@using (Html.BeginForm("Index", "Movies", FormMethod.Get))
{
<b>Search By: </b>@Html.RadioButton("searchBy", "Nome", true) <text> Nome </text>
@Html.RadioButton("searchBy", "Categoria") <text> Categoria </text> <br />
@Html.TextBox("search") <input type="submit" value="Search" class="btn btn-default" />
}
<table class="table table-bordered table-responsive table-hover">
<tr>
<th><b>Nome </b></th>
<th><b>Categoria </b></th>
<th><b>Ano de Lançamento </b></th>
<th><b>Descrição do Filme </b></th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@item.MovieName</td>
<td>@item.MovieCategory</td>
<td>@item.MovieYear</td>
<td>@item.MovieDescription</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.MovieID }) |
@Html.ActionLink("Details", "Details", new { id = item.MovieID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.MovieID })
</td>
</tr>
}
</table>
The new error is not specified in any particular line. It was a web processing error. This is the error:
System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List1[WebApplication3.Models.MovieViewModel]', but this dictionary requires a model item of type 'WebApplication3.Models.MovieViewModel[]'.
Could you add the whole view? but in general the error is that your view expects 1 object and you are passing a list.
– Barbetta
@Barbetta I edited the full view
– Diogo Teixeira