簡體   English   中英

Razor 頁面異步任務返回模態

[英]Razor Pages async task return to modal

我是 Razor 頁面的新手,我真的找不到解決問題的方法。

我有一個模式,我想在其中更新身份角色(添加/刪除用戶)。 異步任務工作正常,我有成員和非成員的列表,但模式在發布后自行關閉。 我怎樣才能防止它(模態關閉)在這種情況下正確的回報是什么?

C#

public async Task<IActionResult> OnPostAddtoRoleAsync()
{
    if(Input != null) 
    { 
    ToolboxRoles role = await _RoleManager.FindByIdAsync(Input.Id);
    List<ToolboxUser> members = new List<ToolboxUser>();
    List<ToolboxUser> nonMembers = new List<ToolboxUser>();
    foreach (ToolboxUser user in _UserManager.Users)
    {
        var list = await _UserManager.IsInRoleAsync(user, role.Name) ? members : nonMembers;
        list.Add(user);
    }

        Input.Role = role; 
        Input.Members = members;
        Input.NonMembers = nonMembers;
    }
    return Page(); //I don't know what is the correct return action here, so the modal stay showed
}

Function 調用:

                           <form method="post">
                                <button asp-page-handler="AddtoRole" asp-route-id="@item.Id" class="btn btn-default" data-id="@item.Id" data-name="@item.Name" data-toggle="modal"
                                        data-target="#EditRole" data-backdrop="static" data-keyboard="false" style="margin-bottom: 10px;">
                                    Update
                                </button>

模態:

<div id="EditRole" class="modal fade" role="dialog">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header" style="background-color: #ffd800">
                <h4 class="modal-title" style="text-align:left">Update Role</h4>
            </div>
            <div class="modal-body" style="background-image: linear-gradient(#ffd800,#fff)">
                <form method="post">
                    <input type="text" id="modal_name" asp-for="Input.RName" />
                    <input type="text" id="modal_id" asp-for="Input.Id" />
                    @if (Model.Input != null)
                    {
                        <div class="row">
                            <div class="col-md-12" style="background-image: radial-gradient(#ffd800,#fff);border: 1px solid #f11322;margin-bottom: 10px;">
                                <h4 id="modal_text1" class="font-weight-bold" style="color: #f11322;"></h4>
                            </div>
                        </div>

                        <table class="table table-bordered table-sm">
                            @if (Model.Input.NonMembers.Count() == 0)
                            {
                                <tr><td colspan="2">All Users Are Members</td></tr>
                            }
                            else
                            {
                                @foreach (ToolboxUser user in Model.Input.NonMembers)
                                {
                                    <tr>
                                        <td>@user.UserName</td>
                                        <td>
                                            <input type="checkbox" name="AddIds" value="@user.Id">
                                        </td>
                                    </tr>
                                }
                            }
                        </table>

                        <div class="row">
                            <div class="col-md-12" style="background-image: radial-gradient(#ffd800,#fff);border: 1px solid #f11322;margin-bottom: 10px;">
                                <h4 id="modal_text2" class="font-weight-bold" style="color: #f11322;"></h4>
                            </div>
                        </div>
                        <table class="table table-bordered table-sm">
                            @if (Model.Input.Members.Count() == 0)
                            {
                                <tr><td colspan="2">All Users Are Members</td></tr>
                            }
                            else
                            {
                                @foreach (ToolboxUser user in Model.Input.Members)
                                {
                                    <tr>
                                        <td>@user.UserName</td>
                                        <td>
                                            <input type="checkbox" name="DeleteIds" value="@user.Id">
                                        </td>
                                    </tr>
                                }
                            }
                        </table>
                    }
                    <button asp-page-handler="UpdateRoles" class="btn btn-default">Save</button>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

以及我用來將值傳遞給模態的 JS:

$('#EditRole').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget); // Button that triggered the modal
    var id = button.data('id');
    var name = button.data('name');  // Extract info from data-* attributes
    // Update the modal's content
    document.getElementById('modal_id').setAttribute('value', id);
    document.getElementById('modal_name').setAttribute('value', name);
    var modal = $(this);
    modal.find('#modal_text1').text('Add Users to ' + name);
    modal.find('#modal_text2').text('Remove Users from ' + name);
});

謝謝, 開發核心

return Page()當你想刷新頁面時你應該調用。 如果添加到列表后一切正常(您確定 Add 已執行),您可以: return Ok()return NoContent()

閱讀文檔: Microsoft 文檔

我認為最好查看整個圖片(您的模態如何處理來自OnPostAddtoRoleAsync()函數的返回響應)。

正如Lazar指出的那樣,更有益的是返回有關用戶是否被正確添加到角色的響應。 在這種情況下,根據用戶發生的情況使用Ok()或其他各種狀態代碼會更有益。

您可以使用event.preventDefault();阻止某些操作在模態中發生。 . 同樣,我們看不到您的前端 razor 頁面是如何處理模態的,因為您沒有在此處提供。 此來源可能有助於使用模態https://www.mikesdotnetting.com/article/349/razor-pages-and-bootstrap-modal-master-details

讓我知道這是否有幫助,謝謝。

我認為您應該將模態體分開並將其作為局部視圖。 使用 jquery ajax 得到局部視圖, append 到模態然后打開它。

我做了一個簡單的demo,你可以參考一下。

索引.cshtml:

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

@Html.AntiForgeryToken()

<button id="Edit" data-id="1" class="btn btn-danger"
        data-backdrop="static" data-keyboard="false" style="margin-bottom: 10px;">
    Update
</button>

<div id="EditRole" class="modal fade" role="dialog">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header" style="background-color: #ffd800">
                <h4 class="modal-title" style="text-align:left">Update Role</h4>
            </div>
            <div class="modal-body" style="background-image: linear-gradient(#ffd800,#fff)">
            
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

@section scripts{
    <script>
        $("#Edit").click(function () {
            var id = $(this).attr('data-id');
            $.ajax({
                type: 'POST',
                url: 'Index?handler=AddtoRole',
                data: {
                    id: id,
                },
                headers: {
                    RequestVerificationToken:
                        $('input:hidden[name="__RequestVerificationToken"]').val()
                },
                success: function (result) {
                    $('.modal-body').html(result);
                    $('#EditRole').modal('show');
                }
            });
        })
    </script>
}

索引.cshtml.cs:

public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;

    public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;
    }

    [BindProperty]
    public Student Input { get; set; }

    public void OnGet()
    {
    }
    
    public IActionResult OnPostAddtoRole()
    {
        Input.Name = "StudentA";
        return Partial("_AddRolePartial",Input); 
    }

    public void OnPost()
    {

    }
}

_AddRolePartial.cshtml:

@model RazorTest.Models.Student

<form method="post">
    <div>
        <label>Id:</label>
        @Model.Id
    </div>
    <div>
        <label>Name:</label>
        @Model.Name
    </div>
    <button asp-page-handler="UpdateRoles" class="btn btn-default">Save</button>
</form>

學生.cs:

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
}

結果:

在此處輸入圖像描述

暫無
暫無

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

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