我正在尝试在我正在开发的网络应用程序中实现一个基本的搜索页面。现在页面看起来像这样
当用户输入姓氏时,将调用 Controller 在后端 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>
}
它应该调用这个 Controller
[HttpPost]
public void SearchAct()
{
Console.WriteLine();
}
最终会执行搜索,然后将结果放在页面上。但是,我无法调用 Controller 。我在 WriteLine 上设置了一个断点,所以我知道它永远不会到达那里,而且我不知道我做错了什么
最佳答案
将名称属性添加到您的文本框。仅基于名称属性构建表单集合。
更改按钮类型以提交,然后它会将您的表单发送到 Controller 。
@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>
}
}
而不是在 Console.WriteLine()
上使用 ViewBag
将您需要的数据发送回 View
引用以下操作
//Get Action for rendering view
public ActionResult SearchAct()
{
return View();
}
[HttpPost]
public ActionResult SearchAct(string nameToFind)
{
ViewBag.SearchKey = nameToFind;
return View();
}
Action 参数名称和文本框名称属性值必须相同否则为null
如果您的表单包含多个文本框,则从 FromCollection
或 Request
[HttpPost]
public ActionResult SearchAct(FormCollection form)
{
ViewBag.SearchKey = form["nameToFind"];
return View();
}
关于c# - 在 ASP.NET MVC 中实现一个简单的搜索功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40478711/