【问题标题】:ASP.NET MVC Search Box Not Posting Back to IndexASP.NET MVC 搜索框未回发到索引
【发布时间】:2016-12-24 19:00:00
【问题描述】:

我有一个基本的 MVC 应用程序,我正在尝试在其上实现一些搜索功能。当我输入数据并单击“搜索”时,url 按预期更新,但索引页面仍然返回所有结果,而不是过滤后的结果。我在下面有我的代码,想知道是否有人能够指出为什么会这样?根据我过去所做的,我不相信我需要一个单独的 Post 方法,但我可能是错的,因为我还是新手。谢谢。

INDEX.CSHTML:

<p>
    @Html.ActionLink("Create New Employee", "Create")
</p>

<form asp-action="Index" method="get">
    <div class="form-actions no-color">
        <p>
            Find by name: <input type="text" name="searchString" value="@ViewBag.CurrentFilter" />
            <input type="submit" value="Search" class="btn btn-default" /> |
            <a asp-action="Index">Back to List</a>
        </p>
    </div>
</form>

控制器:

public ActionResult Index(string searchString)
{
    var person = from p in db.Person
                    select p;

    ViewBag.CurrentFilter = searchString;

    if (!String.IsNullOrEmpty(searchString))
    {
        person = person.Where(s => s.LastName.Contains(searchString));
                                //|| p.FirstName.Contains(searchString));
    }
    return View(db.Person.ToList());
}

点击搜索时返回的URL:

http://localhost:9999/Person/Index?searchString=smith

【问题讨论】:

    标签: c# html asp.net-mvc search


    【解决方案1】:

    因为您将错误的结果返回给视图,该视图指示返回 Persons 表中的所有行并将其传递给视图,因此将最后一行更改为:

    return View(db.Person.ToList());
    

    到:

    return View(person.ToList());
    

    以便将过滤后的结果集返回给视图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-03
      • 1970-01-01
      • 1970-01-01
      • 2011-02-15
      • 1970-01-01
      • 2011-01-19
      相关资源
      最近更新 更多