在ASP.NET MVC中实现简单的搜索功能

Nic*_*ert 3 c# asp.net asp.net-mvc

我正在尝试在正在开发的Web应用程序中实现基本的搜索页面。现在页面看起来像这样

在此处输入图片说明

当用户输入姓氏时,将调用控制器以在后端Microsoft SQL Server数据库中搜索具有该姓氏的所有帐户

现在,HTML表单如下所示

@using (Html.BeginForm("SearchAct", "HomeController", FormMethod.Post))
{
    <form>
        <div>
            Last Name:<br>
            <input type="text" id="nameToFind">

            <input type="button" id="submitId" value="submit" />

        </div>
    </form>
}
Run Code Online (Sandbox Code Playgroud)

应该叫这个控制器

[HttpPost]
public void SearchAct()
{
    Console.WriteLine();
}
Run Code Online (Sandbox Code Playgroud)

最终将执行搜索,然后将结果放在页面上。但是,我无法调用该控制器。我在WriteLine上设置了一个断点,所以我知道它永远不会到达那里,也不知道我在做什么错

小智 5

将名称属性添加到您的文本框。表单集合仅基于名称属性构建。

更改按钮类型以提交,然后它将您的表单发布到控制器。

@using (Html.BeginForm("SearchAct", "Home", FormMethod.Post))
{

    <div>
        Last Name:<br>
        <input type="text" id="nameToFind" name="nameToFind">

        <input type="submit" id="submitId" value="submit" />

    </div>

}

@{
    if(ViewBag.SearchKey != null)
    {
        <span>
            Search Key: @ViewBag.SearchKey
        </span>
    }
}
Run Code Online (Sandbox Code Playgroud)

相反,在Console.WriteLine()使用ViewBag发送您所需要的数据返回查看请参考下行动

//Get Action for rendering view
public ActionResult SearchAct()
{
    return View();
}


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

    return View();
}
Run Code Online (Sandbox Code Playgroud)

动作参数名称和文本框名称属性值必须相同,否则它将 null

如果您的表单包含多个文本框,则读取表单的所有输入值FromCollectionRequest

[HttpPost]
public ActionResult SearchAct(FormCollection form)
{
    ViewBag.SearchKey = form["nameToFind"];

    return View();
}
Run Code Online (Sandbox Code Playgroud)