在页面加载时停止表单post
本文关键字:表单 post 加载 | 更新日期: 2023-09-27 18:10:54
我有一个搜索功能。它搜索注册用户,当你只搜索他们的部分用户名时,它可以工作,然而,这个问题是,当你加载页面时,它基本上搜索,但搜索字符串是空的,这意味着它返回每个用户。我需要让它只在你真正搜索的时候才搜索。但我似乎不知道如何做到这一点。我想基本上我需要阻止表单在页面加载时发布。
@{
Layout = "~/Admin/_SiteLayout.cshtml";
var db = Database.Open("MikZeRCoding2");
var userSearchQuery = "SELECT * FROM [Users] WHERE UserName LIKE '%' + @0 + '%'";
var UsernameSearch = "";
var ErrorMessage = "";
Validation.RequireField("search-username", "lel");
if (IsPost && Validation.IsValid()) {
UsernameSearch = Request.Form["search-username"];
if (UsernameSearch.IsEmpty()) {
ErrorMessage = "You didn't search for anything.";
}
if (!UsernameSearch.IsEmpty() && db.QueryValue(userSearchQuery, UsernameSearch) == null) {
ErrorMessage = "No results for '" + UsernameSearch + "' were found...";
}
else {
}
}
}
<div class="search-users">
<h2>Search users</h2>
<form method="post" action="">
<div class="input-group">
<input type="text" name="search-username" placeholder="Search for a user" class="form-control" />
<span class="input-group-btn">
<button class="btn btn-default glyphicon glyphicon-search" type="button"></button>
</span>
</div>
<input type="submit" value="Search" />
@foreach(var user in db.Query(userSearchQuery, UsernameSearch)) {
<a href="@Href("~/Admin/Accounts/User", user.UserId)"><span>[ @user.UserId ]</span> @user.UserName</a>
}
@if(!ErrorMessage.IsEmpty()) {
<div class="alert alert-danger">@ErrorMessage</div>
@Html.ValidationSummary()
}
</form>
</div>
提前感谢。
您可以将您的用户视图封装在IsPost
-语句中;
@if(IsPost){
foreach(var user in db.Query(userSearchQuery, UsernameSearch)) {
<a href="@Href("~/Admin/Accounts/User", user.UserId)"><span>[ @user.UserId ]</span> @user.UserName</a>
}
}