在页面加载时停止表单帖子

时间:2014-07-01 12:57:11

标签: c# razor asp.net-webpages

我有一个有效的搜索功能。它搜索注册用户,当你只搜索他们的部分用户名时它会起作用,但是,这个问题是,当你加载页面时,它基本上搜索,但搜索字符串是空的,这意味着它返回每个用户。我需要制作它,以便它只在您实际搜索时搜索。但我似乎无法弄清楚如何实现这一目标。我想基本上我需要停止在页面加载时发布表单。

@{
    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>

提前谢谢。

1 个答案:

答案 0 :(得分:0)

您可以在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>
    }
}