簡體   English   中英

帶有 Ajax 按鈕的 Asp.net MVC 從數據庫中檢索數據

[英]Asp.net MVC with Ajax button to retrieve data from database

我有一個 Ajax 按鈕,每當我單擊它時,它都會顯示數據庫中的一條記錄(在我的控制器中,我使用了 .Take(1) )
這是我的觀點:

   <script src="~/Scripts/jquery-3.1.1.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

    <script type="text/javascript" language="javascript">
        function ClearResults() {
            $("#current").empty();
        }
    </script>
    <div class="row">
        <div class="column">
            <h2 class="header-text">CURRENT</h2>
            <div class="current" id="current">
               X000
            </div>
        </div>
    </div>

<div class="row">
    @Ajax.ActionLink(" ", "BtnNext", null, new AjaxOptions
                                {
                                HttpMethod = "GET",
                                InsertionMode = InsertionMode.Replace,
                                UpdateTargetId = "current",
                                LoadingElementId = "loading",
                                OnBegin = "ClearResults",
                                }, new { @class = "Middle-next dim btn btn-large-dim", @id = "Link1"})
</div>

這是我的按鈕控制器:

    public PartialViewResult BtnNext(int count = 0)
    {
        System.Threading.Thread.Sleep(1000);
        var model = db.Queues.OrderBy(x => x.QueueNumber).Take(1);
        return PartialView("_queuenumber", model);
    }

我想在這里做的是 - 每當我單擊下一步按鈕時,它將顯示數據庫中的第一條記錄,然后當我再次單擊它時,它將顯示第二條記錄,依此類推。
(截至目前它只顯示數據庫中的第一個數據)

我想知道這是否可能,我應該使用什么樣的東西來做到這一點?

您將要在客戶端 (JavaScript) 或模型 (Razor) 中跟蹤當前索引,然后將其傳遞到您的控制器方法中,並在每次調用時遞增該值。 從服務器端,您將執行以下操作:

var model = db.Queues.OrderBy(x => x.QueueNumber).Skip(index).Take(1);

我建議發回一個 ViewModel。 對於 Razor 實現,您可以擁有一個包含顯示值、隊列 ID 和索引的 ViewModel。 IE

public class QueueViewModel
{
    public int QueueId { get; set; }
    public int QueueNumber { get; set; }
    public string Name { get; set; } 
    // ..
    public int NextIndex { get; set; }
}

public PartialViewResult BtnNext(int index = 0)
{
    var model = db.Queues.OrderBy(x => x.QueueNumber)
        .Select(x => new QueueViewModel
        {
            QueueId = x.QueueId,
            QueueNumber = x.QueueNumber,
            Name = x.Name,
            NextIndex = index + 1
        })
        .Skip(index).Take(1);
    return PartialView("_queuenumber", model);
}

然后在視圖中會像下面這樣:(對不起,我的剃刀很生銹)

    @Ajax.ActionLink(" ", "BtnNext", "QueueController", 
        new { index = Model.nextIndex },
        new AjaxOptions
        {
            HttpMethod = "GET",
            InsertionMode = InsertionMode.Replace,
            UpdateTargetId = "current",
            LoadingElementId = "loading",
            OnBegin = "ClearResults",
        }, new { @class = "Middle-next dim btn btn-large-dim", @id = "Link1"})

這將需要對行為進行一些驗證,以確保第一個調用以“0”的索引值通過,但希望能給您一些追求的想法。

暫無
暫無

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

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