You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC按LastName搜索功能失效问题求助

修复按LastName筛选的搜索功能

问题根源

原代码存在以下关键缺陷:

  • 表单使用普通按钮,无法触发表单提交
  • 表单提交路径配置错误,无法关联到控制器逻辑
  • 控制器未实现基于LastName的筛选逻辑
  • 视图未保留搜索关键词,用户体验差

具体修复步骤

1. 修正Index.cshtml的表单代码

将普通按钮替换为提交按钮,修正表单提交目标,同时保留搜索输入值:

@model IEnumerable<DEntry.Models.Student>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Student Administration</h2>

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

@using (Html.BeginForm("Index", "Students", FormMethod.Get))
{
    <div>
        Last Name:<br>
        <input type="text" id="nameToFind" name="nameToFind" value="@ViewBag.SearchKey">
        <input type="submit" value="Search" />
    </div>
}

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.StudentID)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LastName)
        </th>
    </tr>

    @foreach (var item in Model)
    {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.StudentID)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.FirstName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.LastName)
    </td>

        @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.Id })
    </td>

</tr>
    }

</table> 

2. 修改StudentsController.cs的Index方法

添加搜索参数接收和筛选逻辑:

// GET: Students
public ActionResult Index(string nameToFind)
{
    var students = db.Students.AsQueryable();

    // 按LastName筛选,忽略大小写(可选)
    if (!string.IsNullOrEmpty(nameToFind))
    {
        students = students.Where(s => s.LastName.IndexOf(nameToFind, StringComparison.OrdinalIgnoreCase) >= 0);
    }

    ViewBag.SearchKey = nameToFind; // 回显搜索关键词
    return View(students.ToList());
}

3. 清理无用代码

删除控制器中未使用的SearchAct方法,避免冗余:

// 移除以下代码块
// public ActionResult SearchAct()
// {
//     return View();
// }

// [HttpPost]
// public ActionResult SearchAct(string nameToFind)
// {
//     ViewBag.SearchKey = nameToFind;
//     return View();
// }

功能说明

  • 输入LastName关键词后点击Search,页面会加载并显示所有LastName包含该关键词的学生记录
  • 搜索使用Get方法,关键词会显示在URL中,支持书签保存
  • 搜索完成后输入框会保留当前关键词,方便二次搜索

内容的提问来源于stack exchange,提问作者khurj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 00:07:07