搜索方法无法在视图中工作

时间:2015-03-07 19:33:38

标签: c# asp.net asp.net-mvc-4 search razor

我在" MusicController":

上创建了这个搜索方法
public ActionResult Search(string search)
        {
            var musicas = from m in db.Musicas select m;

            if (!String.IsNullOrEmpty(search))
            {
                musicas = musicas.Where(s => s.Nome.Contains(search));
               // return RedirectToAction("Search"); //name of view that will return the data
            }
            return View(musicas);
        }

此方法在我的_Layout.cshtml中调用:

     @using (Html.BeginForm("Search", "Music",null, FormMethod.Post, new {@class ="navbar-form navbar-left" , role="search"}))
{
      <div class="form-group">
           @Html.TextBox("search")
      </div>
      button type="submit" class="btn btn-default" value="search">Submit</button>
} 

因此,当用户在TextBox中放置一个值并单击“提交”按钮时,会重定向到此视图:

@model IEnumerable<TestTcc2.Models.Musica>

@{
    ViewBag.Title = "Search";
    Layout = "~/Views/Shared/_LayoutOuvinte.cshtml";
}
<h2>Search</h2>
<table>
       <tr>
        <th>
            <span>Genero</span>
        </th>

        <th>
            <span>Nome</span>
        </th>
        <th>
            <span>Artista</span>
        </th>
        <th>
            <span>Preço</span>
        </th>
        <th></th>
    </tr>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.genero.Nome)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Nome)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.NomeArtista)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Preco)
        </td>
        <td>
            @Html.ActionLink("Play", "", new { path = item.path }) |
        </td>
    </tr>
}
</table>

在这个视图中,用户应该看到搜索方法的结果,我认为我需要在if之后添加一个if&#34; if(item.Nome ==&#34; searchResult&#34;)& #34;,但我不知道将搜索方法的结果放在桌面上的最佳方法是什么。

有人可以帮帮我吗?基本上,我需要在搜索视图的表格中返回搜索方法的结果。

1 个答案:

答案 0 :(得分:0)

没有看到您的模型类和相关项目,我只能建议您查看返回到视图的内容。

调试您的Controller并在该行上放置一个断点:

return View(musicas);

检查音乐中的内容,那里的子项目是否可导航?您使用过:

@Html.DisplayFor(modelItem => item.genero.Nome)

如果genero子项目不可用,您将收到错误。

此外,db.Musicas与:

相同
IEnumerable<TestTcc2.Models.Musica>

从数据库/数据集等获取数据是一回事,但它需要与页面上使用的模型结构相同。

相关问题