-Asp.Net- 如何从控制器调用对话框?

-Asp.Net- how can I call a dialog from the controller?

好的,我想知道是否可以从控制器调用对话框并学习如何操作。

我知道通常不建议这样做,因为控制器 运行 相对于视图是异步的,但在这种情况下,我真的需要这样做,因为它会大大简化代码并使我的网页 运行 慢得多。

自从这样做以来,如果我在控制器中将用户发送到不同的视图,如果满足某些条件,则与控制器接收的数据没有太大区别,如下所示:

[HttpPost]
 public IActionResult Create(List<Int> list)
{

//does stuff with the data in list and then if X happens:
 return View("VIEW RETURNED");

}

所以我想要的是,不要发生这种情况,如果在控制器中满足某些条件,则将用户发送到不同的视图,我希望这使一个对话框出现在视图中,如下所示:

https://miro.medium.com/max/2048/1*8vxEG0_9CBNboImHBhEP_w.png

对话框在 html 代码中显示了一些信息,如果我按“取消”会发生一些事情,如果我按下接受其他事情,它会发生并且信息会发送回控制器并进行一些更改。

这样做并从控制器管理对话框真的不可能吗?我在整个互联网上搜索过,但没有找到任何相关信息。

The Dialog shows some information in html code and if I press "Cancel" something happens, and if I press accept something else it happens and the information is sent back to the Controller with some changes.

Is it really impossible to do this and manage the Dialogs from the controller? I've searched all over the internet and haven't found anything about it.

根据你的描述,你想使用弹出对话框来制作一个条件(取消和删除),如果用户选择其中一个,它应该在控制器中做一些事情。如果是这样,你可以使用 Bootstrap Modal 显示对话框,并使用 JQuery Ajax 调用 action 方法并执行某些操作,代码如下:

Index.cshtml:在BootstrapModal中添加两个按钮,使用JQuery捕获按钮点击事件,然后使用JQueryajax调用操作方法并在 Ajax 成功函数中执行某些操作。

<!-- Button to Open the Modal -->
<button id="btnOpenModal" type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
    Open modal
</button>

<!-- The Modal -->
<div class="modal" id="myModal">
    <div class="modal-dialog">
        <div class="modal-content">

            <!-- Modal Header -->
            <div class="modal-header">
                <h4 class="modal-title">Modal Heading</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>

            <!-- Modal body -->
            <div class="modal-body" id="modalcontent">
            
            </div>

            <!-- Modal footer -->
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger">Yes, delete it</button>
                @*<button type="button" class="btn btn-danger" data-dismiss="modal">Yes</button>*@
            </div> 
        </div>
    </div>
</div>

@section Scripts{ 
    <script>
        $(function () {
            $("#btnOpenModal").click(function () {
                // call the action method, in the success function add the return data in the Modal content.
                $.ajax({
                    type: "Get",
                    url: "/Home/GetViewContent",  //remember change the controller to your owns.  
                    success: function (data) {
                        console.log(data)
                        $('#modalcontent').html(data);
                    }, 
                    error: function (response) {
                        console.log(response.responseText);
                    }
                });
            });
            //Popup Modal's Cancel button click
            $("#myModal").on("click", ".btn-default", function () {
                //since the button element using the data-dismiss attribute, there is no need to close the Modal via jquery.
                // code. using jquery ajax do something
                alert("Cancel button click");
            });
            //Popup Modal's  delete button click
            $("#myModal").on("click", ".btn-danger", function () {
                // code
                alert("Delete button click");

                //using the following code to close the popup modal.                
                $('#myModal').modal('hide') //or  $("#myModal").modal('toggle');

                //using JQuery Ajax to call the action method.
            });
        });
    </script>
}

HomeController.cs:

    public IActionResult Index()
    {
        return View();
    }
    public IActionResult GetViewContent()
    {
        return Ok("You'll lose all responses data. Are you sure you want to delete them?");
    }

使用默认值_Layout.cshtml

[注意] 在上面的 Asp.net 核心 MVC 应用程序中,我使用默认的 template/layout 并且它已经使用了 Bootstrap 引用(JS+CSS),如果您不使用默认的 template/layout,您应该添加相关的 BootStrap 和 JQuery 参考。

截图如下:

更新:

要使用JQuery ajax调用使用[ValidateAntiForgeryToken]属性的action方法,我们应该在请求header中添加RequestVerificationToken。请检查以下代码:

在Index.cshtml中添加如下代码:

    @model WebApplication.Models.Book

    <form asp-action="Create">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="BookId" class="control-label"></label>
            <input asp-for="BookId" class="form-control" />
            <span asp-validation-for="BookId" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="BookName" class="control-label"></label>
            <input asp-for="BookName" class="form-control" />
            <span asp-validation-for="BookName" class="text-danger"></span>
        </div> 
    </form>

并且,在模态页脚中添加以下创建按钮

 <button type="button"  class="btn btn-primary btncreate" data-dismiss="modal">Create</button>

Book.cs:

public class Book
{
    public int BookId { get; set; }
    public string BookName { get; set; }
}

创建操作:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(Book book)
    {
        if (ModelState.IsValid)
        {
            var data = book;

            return Ok("Insert Success");
        }
        return View();
    }

然后,在创建按钮点击事件中,创建一个JSobject并发送给action方法:

        //Popup Modal's Create button click
        $("#myModal").on("click", ".btncreate", function () { 
            //using JQuery Ajax to call the action method.
            var book = {};
            book.BookName = $("#BookName").val();
            book.BookId = $("#BookId").val();
            $.ajax({
                url: "/Home/Create",
                type: "POST",
                data: book, 
                beforeSend: function (request) {
                    request.setRequestHeader(
                        "RequestVerificationToken",
                        $("[name='__RequestVerificationToken']").val());
                },
                success: function (response) {
                    alert(response);
                }
            });
        });

截图如下: