簡體   English   中英

如何使用 ajax asp.net 內核從數據庫中獲取數據

[英]how to get data from database using ajax asp.net core

根據以下代碼,我在索引 Model 中創建了 Get Handler

public IActionResult OnGetCustomer(CustomerSearchModel searchModel)
        {
            
            CustomerCombine combine = new CustomerCombine
            {
                MyViewModels = _customerApplication.GetAll(searchModel)
            };

            return Partial("./Customer", combine);
        }

這是我的 Razor 視圖:

@model CustomerCombine
 <form asp-page="./Index" asp-page-handler="Customer"
                   
                      method="get"
                      data-ajax="true"
                      data-callback=""
                      data-action="Refresh"
                     >
                    <div class="form-group">
                        <input asp-for="@Model.MySearchModel.FullName" class="form-control " placeholder="search..." />
                    </div>
                    <button class="customer-submit btn btn-success" type="submit">جستجو</button>
                </form>
<table>
 @foreach (var item in @Model.MyViewModels)
                {
                    <tr>
                        <td>@item.Id</td>
                        <td>@item.FullName</td>
                        <td>@item.Mobile</td>
                        <td>@item.Email</td>
                        <td>@item.Address</td>
                        <td>@item.Image</td>
                    </tr>
                }
</table>

我的模態顯示成功,我可以看到我的數據庫的數據,但是當我填寫搜索字段並單擊搜索按鈕時,沒有任何反應可以幫助我嗎?:)

這是我的jquey代碼:我對Jquery一無所知,這些代碼已經准備好,現在我不知道我應該如何使用它

    $(document).on("submit",
        'form[data-ajax="true"]',
        function (e) {
            e.preventDefault();
            var form = $(this);
            const method = form.attr("method").toLocaleLowerCase();
            const url = form.attr("action");
            var action = form.attr("data-action");

            if (method === "get") {
                const data = form.serializeArray();
                $.get(url,
                    data,
                    function (data) {
                        CallBackHandler(data, action, form);
                    });
            } else {
                var formData = new FormData(this);
                $.ajax({
                    url: url,
                    type: "post",
                    data: formData,
                    enctype: "multipart/form-data",
                    dataType: "json",
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        CallBackHandler(data, action, form);
                    },
                    error: function (data) {
                        alert("خطایی رخ داده است. لطفا با مدیر سیستم تماس بگیرید.");
                    }
                });
            }
            return false;
        });
});

function CallBackHandler(data, action, form) {
    switch (action) {
        case "Message":
            alert(data.Message);
            break;
        case "Refresh":
            if (data.isSucceced) {
                window.location.reload();
            } else {
                alert(data.message);
            }
            break;
        case "RefereshList":
            {
                hideModal();
                const refereshUrl = form.attr("data-refereshurl");
                const refereshDiv = form.attr("data-refereshdiv");
                get(refereshUrl, refereshDiv);
            }
            break;
        case "setValue":
            {
                const element = form.data("element");
                $(`#${element}`).html(data);
            }
            break;
        default:
    }
}

function get(url, refereshDiv) {
    const searchModel = window.location.search;
    $.get(url,
        searchModel,
        function (result) {
            $("#" + refereshDiv).html(result);
        });
}

1. $.get()的第三個參數是成功的function。

2.您的回發數據中沒有isSucceced屬性。 回發數據是部分視圖 html 代碼。 你需要使用$("xxx").html(data); 更新部分視圖代碼。

3.Model Binding 按名稱綁定屬性, <input asp-for="@Model.MySearchModel.FullName"/>CustomerSearchModel searchModel不匹配。

public IActionResult OnGetCustomer(CustomerSearchModel MySearchModel)

整個工作演示和更多細節我已經評論了代碼請仔細檢查:

Model

public class CustomerCombine
{
    public List<MyViewModel> MyViewModels { get; set; }
    public CustomerSearchModel MySearchModel { get; set; }
}
public class CustomerSearchModel
{
    public string FullName { get; set; }
}
public class MyViewModel
{
    public int Id { get; set; }
    public string FullName { get; set; }
    public string Email { get; set; }
    public string Mobile { get; set; }
    public string Address { get; set; }
    public string Image { get; set; }
}

查看(索引.cshtml)

@page
@model IndexModel
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
  Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        @Html.Partial("Customer",Model.CustomerCombine)
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
 
@section Scripts
{
    <script>
          $(document).on("submit",'form[data-ajax="true"]',function (e) {
            e.preventDefault();
            var form = $(this);
            const method = form.attr("method").toLocaleLowerCase();
            const url = form.attr("action");
            var action = form.attr("data-action");

            if (method === "get") {
                const data = form.serializeArray();
                $.get(url,data,function (data) { 
                        console.log(data);    //you can check the response data in Console panel
                        CallBackHandler(data, action, form);
                    });
            } else {
                var formData = new FormData(this);
                $.ajax({
                    url: url,
                    type: "post",
                    data: formData,
                    enctype: "multipart/form-data",
                    dataType: "json",
                    processData: false,
                    contentType: false,
                    success: function (data) {                        
                        CallBackHandler(data, action, form);
                    },
                    error: function (data) {
                        alert("خطایی رخ داده است. لطفا با مدیر سیستم تماس بگیرید.");
                    }
                });
            }
            return false;
        });
//});    //remove this.......

    function CallBackHandler(data, action, form) {
        switch (action) {
            case "Message":
                alert(data.Message);  
                break;
            case "Refresh":
                $(".modal-body").html(data);      //modify here....
                break;
            case "RefereshList":
                {
                    hideModal();
                    const refereshUrl = form.attr("data-refereshurl");
                    const refereshDiv = form.attr("data-refereshdiv");
                    get(refereshUrl, refereshDiv);
                }
                break;
            case "setValue":
                {
                    const element = form.data("element");
                    $(`#${element}`).html(data);
                }
                break;
            default:
        }
    }

    function get(url, refereshDiv) {
        const searchModel = window.location.search;
        $.get(url,
            searchModel,
            function (result) {
                $("#" + refereshDiv).html(result);
            });
    }
    </script>
}

局部視圖不會改變任何東西

@model CustomerCombine

 <form asp-page="./Index" asp-page-handler="Customer"
                   
                      method="get"
                      data-ajax="true"
                      data-callback=""
                      data-action="Refresh"
                     >
                    <div class="form-group">
                        <input asp-for="@Model.MySearchModel.FullName" class="form-control " placeholder="search..." />
                    </div>
                    <button class="customer-submit btn btn-success" type="submit">جستجو</button>
                </form>
<table>
 @foreach (var item in @Model.MyViewModels)
                {
                    <tr>
                        <td>@item.Id</td>
                        <td>@item.FullName</td>
                        <td>@item.Mobile</td>
                        <td>@item.Email</td>
                        <td>@item.Address</td>
                        <td>@item.Image</td>
                    </tr>
                }
</table>

頁面模型

public IActionResult OnGetCustomer(CustomerSearchModel MySearchModel)//change here....
{

    CustomerCombine combine = new CustomerCombine
    {
        MyViewModels =  _customerApplication.GetAll(searchModel) //be sure here contains value...
    };

    return Partial("./Customer", combine);
}

結果:

在此處輸入圖像描述

暫無
暫無

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

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