簡體   English   中英

使用JS和ASP.NET MVC的Web網格搜索功能

[英]Web grid search function using JS and ASP.NET MVC

我正在使用ASP.NET MVC。 我嘗試實現搜索框

我有一個輸入框和一個按鈕:

<div>
    <input type="text" name="Search" id="Search" />
    <input type="submit" value="Search" id="SearchButton" />
</div>

然后我使用JS接收用戶輸入並觸發一個函數:

$(document).ready(function () {
    $('#SearchButton').click(function Search() {
        $.ajax({
            url: '@Url.Action("Search", "PCA")',
            data: { AutoCribItemID: $('#Search').val() },
            type: "POST",
            dataType: "json",
            success: function (result) {
                var data = new Array();
                for (var i = 0; i < result.Data.length; i++) {
                    data.push(result.Data[i]);
                }

                loadData(data);
            },
            error: function () {
                alert("Failed! Please try again.");
            }
        });
    });
});

然后在后端,有一個響應方法:

[HttpPost, ActionName("Search")]
public JsonResult Search(string AutoCribItemID) {
    List<PCAModel> allRecords = new List<PCAModel>();
    allRecords = db.elements.Where(model => model.AutoCribItemID.Contains(AutoCribItemID)).ToList();
    return Json(new { Data = allRecords }, JsonRequestBehavior.AllowGet);
}

您可以看到此C#方法將列表返回到前端。 然后我想要做的是在搜索到用戶后顯示所有數據。

這是搜索后顯示數據的方法:

function loadData(result) {
    var table = $('<table id="indexTable"></table>');
    var thead = $('<thead></thead>');
    var trow = $('<tr class="header"></tr>');
    trow.append('<th>EffectiveDate</th>');
    trow.append('<th>ChangeAgree</th>');
    trow.append('<th>Client</th>');
    trow.append('<th>Installation</th>');
    trow.append('<th>AutoCribItemID</th>');
    trow.append('<th>RGBSupplier</th>');
    trow.append('<th>Price</th>');
    trow.append('<th>SubmitDate</th>');
    trow.append('<th>WINUserName</th>');
    trow.append('<th>Export</th>');
    thead.append(trow);
    table.append(thead);
    var tbody = $('<tbody></tbody>');
    for (var i = 0; i < result.length; i++) {
        tbody.append(result[i]);
    }

    table.append(tbody);

    $('#indexTableBody').html(table);
    location.reload();
}

注意:上面的“結果”參數來自后端的C#函數。

問題是,網頁顯示表中的所有記錄,而不是顯示搜索的數據。 我只需要在網格搜索后顯示數據。

在不知道AutoCribItemID的結構的情況下,我的猜測是,因為你在where子句中使用.Contains,它會返回與該搜索詞匹配的任何東西 因此,例如,如果您有整數ID並且有人搜索“1”,它將返回包含數字1的任何ID,包括1,10,11,12,13等。您可能希望使用相等比較來代替,即model.AutoCribItemID == AutoCribItemID

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM