简体   繁体   English

在 Bootstrap 模态 .NET Core 3.1 C# 中返回 ViewComponent

[英]Returning ViewComponent inside Bootstrap modal .NET Core 3.1 C#

I am bulding an ASP.NET Core MVC Application.我正在构建一个 ASP.NET Core MVC 应用程序。 (.NET Core 3.1) (.NET 核心 3.1)

On one of the views - Results.chtml (with huge amount of DB rows shown), I decided to display more details of each row on the Bootstrap modal popup.在其中一个视图 - Results.chtml(显示了大量 DB 行)上,我决定在 Bootstrap 模式弹出窗口中显示每行的更多详细信息

So - each row in this view has a button that displays a modal with the appropriate data binded by button property.因此 - 此视图中的每一行都有一个按钮,该按钮显示具有由按钮属性绑定的适当数据的模式。 I am loading the ViewComponent to this modal body by use of 'on('show.bs.modal') and $.get() - I call the action in my controller and the action returns the ViewComponent .我正在使用'on('show.bs.modal')$.get()将 ViewComponent 加载到这个模态主体 -我在我的控制器中调用动作,动作返回 ViewComponent

A proper ViewComponent loads up, with all the data correctly fetched.The problem is:正确的 ViewComponent 加载,所有数据正确获取。问题是:

Everything related to a jQuery DataTables plugin dissapeared from the modal.与 jQuery DataTables 插件相关的所有内容都从模式中消失了。 (When I was displaying it in the separate page - it worked perfectly) (当我在单独的页面中显示它时 - 它工作得很好)


What I tried to change我试图改变的

At first, I had the jQuery DataTables script loaded in this ViewComponent's .cshtml file, but it was behaving totally unexpectable.起初,我在这个 ViewComponent 的 .cshtml 文件中加载了 jQuery DataTables 脚本,但它的行为完全出乎意料。 Once sorting and filtering options showed up, once not.一旦出现排序和过滤选项,就没有。 I decided to change it and I moved jQuery DataTables scripts to the main view - Results.cshtml .我决定更改它,并将 jQuery DataTables 脚本移至主视图 - Results.cshtml Now: it doesn't work, but...the error saying that "dataTable() isn't recognized method" is not present in the JS console!现在:它不起作用,但是……JS 控制台中不存在“dataTable() 不是识别方法”的错误信息! It means that it loaded the DataTables' scripts successfully...这意味着它成功加载了数据表的脚本......

Where should I load DataTables scripts?我应该在哪里加载 DataTables 脚本? They are now laoded in the Layout.cshtml file.它们现在位于 Layout.cshtml 文件中。 Is it possible that the order of this loadings makes it impossible to use DataTables inside of the modal?这种加载的顺序是否可能导致无法在模态内使用 DataTables? Is it even the source of my problems它甚至是我问题的根源吗

Crutial code parts关键代码部分

  1. Layout.cshtml布局.cshtml 在此处输入图片说明

  2. Script section inside the Results.cshtml (with a moved fragment at the end - dataTables(...)) Results.cshtml 中的脚本部分(末尾有一个移动的片段 - dataTables(...))

     $(function () { $(document).ajaxStart(function() { $("#loading").show(); }); $(document).ajaxStop(function() { $("#loading").hide(); }); $('#exampleModal').on('show.bs.modal', function (event) { var container = $("#receiptDetailsView"); var clickedRow = $(event.relatedTarget); var accountId = clickedRow.data('accountidvalue'); $.get("/Receipts/" + accountId, function (data) { container.html(data); }); }); $("#exampleModal").on("hidden.bs.modal", function () { $("#receiptDetailsView").html(""); }); $('#sortableReceiptsTable').dataTable({ "filter": true, "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]] }); });

  3. Modal markup in Results.cshtml Results.cshtml 中的模态标记在此处输入图片说明

  4. Action called by AJAX get: AJAX 调用的操作获取:

     [HttpGet("receipts/{accountId}")] public IActionResult ShowReceipts([FromRoute]string accountId) { // invokes the InvokeAsync method of ReceiptsViewComponent return ViewComponent("Receipts", accountId); }
  5. InvokeAsync Method inside of ViewComponent class: ViewComponent 类中的 InvokeAsync 方法:

     public async Task<IViewComponentResult> InvokeAsync(string accountId) { var allReceipts = await _cosmosDbService.GetReceiptsByAccountIdAsync(accountId); List<ReceiptViewModel> recVMs = allReceipts.Select(u => u.ToReceiptViewModel()).ToList(); return View("Receipts", recVMs); }

Thank You!谢谢你!

Here is a working demo , you could refer to:这是一个工作演示,您可以参考:

Model:模型:

public class Link
{
    public int Id { get; set; }
    public string Title { get; set; }

    public string Url { get; set; }
    public string Description { get; set; }

    public int CategoryId { get; set; }
    public Category Category { get; set; }
}
public class Category
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int Order { get; set; }

    public ICollection<Link> Links { get; set; }
}

JS inMain view JS 在主视图中

@section Scripts
{
<script>
        $(function () {

            $(document).ajaxStart(function() {
              $("#loading").show();
            });

            $(document).ajaxStop(function() {
              $("#loading").hide();
            });

            $('#exampleModal').on('show.bs.modal', function (event) {
                var container = $("#receiptDetailsView");
                var clickedRow = $(event.relatedTarget);
                var accountId = clickedRow.data('accountidvalue');
                $.get("/Receipts/" + accountId, function (data){container.html(data);});

            });  

            $("#exampleModal").on("hidden.bs.modal", function () {
                $("#receiptDetailsView").html("");
            });
        });
</script>
}

View Component class查看组件类

    public async Task<IViewComponentResult> InvokeAsync(string accountId)
    {
        var categoryId = Convert.ToInt32(accountId);
        var model = _context.Link.Where(l => l.CategoryId == categoryId).ToList();
        return View(model);
    }

Default view of view component视图组件的默认视图

@model List<MVCDemo3_1.Models.Links.Link>

<div class="container">
<br />
<div style="width:90%; margin:0 auto;">
    <table id="sortableReceiptsTable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
        <thead>
            <tr>
                <th>Title</th>
                <th>Description</th>
                <th>action</th>
            </tr>
        </thead>
    </table>
</div>
</div>

<script type="text/javascript">
    $(document).ready(function () {
        $('#sortableReceiptsTable').DataTable({
            data: @Html.Raw(Json.Serialize(Model)),
            columns: [
                { 'data': 'title' },
                { 'data': 'description' },
                {
                    'data': 'id',
                    'render': function (data) {
                        {
                            return '<a  href="#" title="ویرایش" style="margin-left:10px" class="btn btn-success button"  onclick="openModal(' + data + ');"><i class="fa fa-edit"></i></a><a  href="#" title="حذف" style="margin-right:10px"  class="btn btn-danger button"  onclick="deleteUser(' + data + ')"><i class="fa fa-trash"></i></a>'
                        }
                    },
                }
            ]
        });
    });
</script>

Result:结果: 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM