我有一個 Asp.Net Core MVC webapp,它有一個 IEnumerable 物件,它在螢屏上顯示為一列按鈕。我還有一個搜索欄,我希望能夠根據按鈕是否包含搜索字串來過濾按鈕。
我讓它作業,這樣我就可以通過附加 ?searchString="Whatever" 來手動更改 url 并且它可以正常作業。但是,如何根據文本框中當前的內容使表單帖子包含 searchString 值?我嘗試過使用輸入框的 id 的變體,但無法弄清楚。
這基本上是它的樣子。
<form method="post" action="@Url.Action("Index", "Home", new { searchString = "What goes here?"})">
<button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>
<input class="form-control me-sm-2" type="text" placeholder="Enter Name">
</form>
我可以在 url.action 中添加一些內容來捕獲文本框的內容并將其與帖子一起發送嗎?還是我需要嘗試其他實作?
uj5u.com熱心網友回復:
提交表單時,您可以系結表單輸入,以便控制器能夠讀取它。為此,您至少需要向name輸入添加一個屬性,使其看起來像:
<input class="form-control me-sm-2" type="text" name="search" placeholder="Enter Name">
然后,在控制器上,您可以將該值添加為引數,如下所示:
public IActionResult Index( string? search = null )
您也不需要searchString在呼叫中保留物件Url.Action。
隨著您的表單的增長,最好最終轉向模型系結,您可能有一個 ViewModel,例如:
public class SearchViewModel{
public string Search { get; set;}
public string OtherThing { get; set}
}
然后在您的控制器上,您將執行以下操作:
public IActionResult Index( SearchViewModel viewModel )
在您的表單上,您可以使用標簽助手:
@model SearchViewModel At the top of the page
<form method="post" action="@Url.Action("Index", "Home")">
<button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>
<input class="form-control me-sm-2" type="text" asp-for="Search" placeholder="Enter Name">
</form>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/514894.html
標籤:htmlasp.net 核心邮政asp.net-core-mvc
上一篇:活動記錄查詢
