在捕获块中打开模式对话

时间:2018-11-11 19:07:54

标签: c# asp.net-core modal-dialog

我的操作中包含此代码

var singedUser = HttpContext.User.Identity.Name;

        try
        {
            _purchaseService.PurchaseCard(singedUser, cardName);
        }
        catch
        {

        }

而且我希望仅在代码进入catch块时才打开

<div id="Modal" class="modal fade" role="dialog">
    <div class="modal-dialog">

        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Purchasing Card</h4>
            </div>
            <div class="modal-body">
                <p>You have unsufficient funds!</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            </div>
        </div>

    </div>
</div>

这是我的按钮

<a class="button btn btn-success" 
    asp-controller="Store" asp-action="Buy" 
    asp-route-data ="@card.Name">Buy (@card.Price coins)</a>

如果有人告诉我如何仅在代码进入catch块的情况下才能在同一页面中打开此对话框,我将不胜感激

2 个答案:

答案 0 :(得分:1)

您还可以使用ajax调用返回部分视图并将其添加到DOM。设置模式以加载部分视图实际上很简单:

  1. 创建部分视图:_ModalContent.cshtml

    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">Purchasing Card</h4>
        </div>
        <div class="modal-body">
            <p>You have unsufficient funds!</p>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        </div>
    </div>
    
  2. 修改索引页面:

    <a id="button1" class="button btn btn-success" 
    asp-controller="Store" asp-action="Buy" 
    asp-route-data ="@card.Name">Buy (@card.Price coins)</a>
    
    <div id="myModal"></div>
    
    @section Scripts{
    
    <script type="text/javascript">
    $(function () {
        $.ajaxSetup({ cache: false });
        $("#button1").on("click", function (e) {
            $('#myModal').load(this.href, function () {
                $('#Modal').modal({
                    keyboard: true
                }, 'show');
            });
            return false;
        });
    });
    </script>
    }
    
  3. 控制器功能:

    public IActionResult buy(string data)
    {
        .....
        {
    
            return PartialView("_ModalContent");
        }
    }
    

答案 1 :(得分:0)

我将通过控制器/动作上的ViewBag传递变量。控制器中的内容如下:

            var singedUser = HttpContext.User.Identity.Name;

        try
        {
            _purchaseService.PurchaseCard(singedUser, cardName);
        }
        catch
        {
            ViewBag.ShowModal = false;
        }

然后切换是否触发JQuery以在视图的脚本部分中显示Modal:

@section Scripts{
<script>
    @if(ViewBag.ShowModal == true){
        @Html.Raw("$('#Modal').modal('show');");
    }
</script>
}