【问题标题】:MVC Loading Controller Action with Authorize Tag from Different View使用来自不同视图的授权标记的 MVC 加载控制器操作
【发布时间】:2017-01-12 16:28:58
【问题描述】:

我创建了一个引导模式,它调用控制器操作来加载模式内的视图。

控制器操作有一个授权标签,这意味着每当您加载默认视图(而不是模式)时,它都会要求您登录,模式包含创建新功能,我不希望匿名用户访问因此授权标签。

但用户无法访问任何内容,因为视图正在调用创建控制器操作(具有授权标记),即使模式尚未打开。

<div id="myModal" class="modal fade" role="dialog">
    <div class="modal-dialog" style="width: 70%;">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h3 class="modal-title text-center">Create New Connecting Rod</h3>
            </div>
            <div class="modal-body" id="createModal">
                @Html.Action("Create")
            </div>
        </div>
    </div>
</div>

上面的代码是用于调用创建控制器动作的代码,我只希望在单击模态按钮时调用控制器动作,而不是在页面首次加载时调用。

[Authorize]
public ActionResult Create()
{
    return PartialView();
}

这是我创建控制器动作中唯一的代码

我曾尝试使用一些 JQuery 仅在按下按钮后才加载动作,但这似乎也不起作用。

$(document).on("click", "#createNew", function (e) {
    alert("hello");
    $('@Html.Action("Create")').appendTo('#createModal');
});

【问题讨论】:

    标签: jquery asp.net-mvc bootstrap-modal html-helper


    【解决方案1】:

    不要在页面加载时加载您的授权内容,因为用户可能已登录或匿名。而是在用户单击链接或按钮时加载内容,然后调用打开模式对话框方法。

    <div id="myModal" class="modal fade" role="dialog">
        <div class="modal-dialog" style="width: 70%;">
    
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h3 class="modal-title text-center">Create New Connecting Rod</h3>
                </div>
                <div class="modal-body" id="createModal">
                    <!-- have some loading icon here by default -->
                </div>
            </div>
        </div>
    </div>
    

    如果你有一个按钮可以打开对话框,编写以下脚本

    <script>
    $(function{
     $("your_button").click(function(){
    
      // load content of your url @Url.Action("Create") in div "#createModal"
    // and then open the dialog
    
         $.ajax({       
                        url: "@Url.Action("Create")",
                        cache: false,
                        dataType: "html",
                        success: function (data) {
                            $("#createModal").html(data);
                    }
                });
    
                $("#myModal").modal().show();
    
         });
    });
    </script>
    

    【讨论】:

    • 您好,对不起,我忘了提及我尝试过这样的事情,但它仍然无法正常工作,我将编辑我的问题以向您展示
    • 确保你的调用中有 cache: false ,否则你每次都会得到缓存的内容
    • 我必须添加 ajax 才能做到这一点吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    相关资源
    最近更新 更多