【问题标题】:-Asp.Net- how can I call a dialog from the controller?-Asp.Net- 如何从控制器调用对话框?
【发布时间】:2021-01-17 04:50:11
【问题描述】:

好的,我想知道是否可以从 Controller 调用 Dialog 并学习如何操作。

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

既然这样做了,那么如果我在控制器中将用户发送到不同的视图,如果满足某些条件,控制器接收到的数据,就像这样:

[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 代码中显示一些信息,如果我按下“取消”,就会发生一些事情,如果我按下接受,就会发生其他事情,并且信息会被发送回控制器并进行一些更改。

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

【问题讨论】:

    标签: asp.net-core razor controller dialog modal-dialog


    【解决方案1】:

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

    真的不可能做到这一点并从 控制器?我在整个互联网上搜索过,但没有找到 关于它的任何东西。

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

    Index.cshtml:在Bootstrap Modal中添加两个按钮,用JQuery捕捉按钮点击事件,然后用JQuery ajax调用action方法,在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 Core MVC 应用程序中,我使用的是默认模板/布局,它已经使用了 Bootstrap 引用(JS+CSS),如果你没有使用默认模板/布局,你应该添加相关的 BootStrap 和 JQuery 引用。

    截图如下:

    更新

    要使用JQuery ajax 调用使用[ValidateAntiForgeryToken] 属性的action 方法,我们应该在请求头中添加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();
        }
    

    然后,在创建按钮点击事件中,创建一个JS对象并发送到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);
                    }
                });
            });
    

    截图如下:

    【讨论】:

    • 只是为了确保我没有应用错误的代码,BootStrap 和 JQuery 引用是什么?我没有使用默认模板/布局。
    • 请检查the screenshot,当我们使用MVC模板创建.net核心应用程序时,它已经安装了JQuery和BootStrap客户端库,您可以从wwwroot文件夹中找到它们。而在_Layout.cshtml页面中,我们可以看到已经添加了JQuery和BootStrap的JS和CSS引用。所以,在主页面中,如果你使用_Layout.cshtml,就不需要再添加JQuery和Bootstrap引用了.如果不使用主页面中的_Layout.cshtml页面,则必须在JS脚本之前添加JQuery和Bootstrap引用。
    • 嗨!如果你还在那儿,我在向 GetViewContent() 方法发送信息时遇到问题,现在我的控制器有类似:“ [HttpPost] [ValidateAntiForgeryToken] public IActionResult GetViewContent(CcViewModel data) {” 但这没有收到来自模型的信息,"
      " 所做的事情,这导致了 Create 方法;我做错了什么?
    • ok 发生的事情是模型没有被发送到控制器方法,所以模型没有绑定。我在 Create 方法中接收模型的方式如下: === [HttpPost] [ValidateAntiForgeryToken] public async Task Create(CcViewModel data) {} === 我的按钮在里面:===
      === ;那么,如何将模型绑定到 GetViewContent() 方法中?
    • 嗨@MarcosFuente,请检查上述回复中的更新。要使用 JQuery Ajax 调用使用 [ValidateAntiForgeryToken] 属性的操作方法,我们应该在请求头中添加 RequestVerificationToken。然后,创建一个 JS 对象并填充值,然后发送到 action 方法。
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签