使用Ajax刷新ASP.NET MVC中的引导模式

Refreshing the bootstrap modal in ASP.NET MVC with Ajax

本文关键字:模式 MVC Ajax 刷新 ASP NET 使用      更新时间:2023-09-26

我有一个引导模式。当我单击提交按钮时,页面会被刷新并丢失模式。我想在点击提交按钮后继续使用模式来显示成功消息或错误消息。我是MVC的新手,我搞不明白。

这是我的模式

<div class="modal fade" id="signin_modal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class=" modal-header">
                Create An Account
            </div>
            <div class="modal-body">
                @using (Html.BeginForm("Login", "Home", FormMethod.Post))
                {
                    <table>

                        <tr><td>@Html.Label("username", null, new { style = " font-size:12px; font-weight:normal; font-family:consolas; " })</td></tr>
                        <tr><td>@Html.TextBox("name", null, new { style = " width:200px; height:30px; " })</td></tr>

                        <tr> </tr>
                        <tr><td>@Html.Label("password", null, new { style = " font-size:12px; font-weight:normal; font-family:consolas; " })</td></tr>
                        <tr><td>@Html.TextBox("password", null, new { style = " width:200px; height:30px " })</td></tr>
                    </table>
                }
            </div>
            <div class="modal-footer">
                <button type="submit" class="btn btn-success">Sign in</button>
                @*<button type="reset" class="btn btn-warning">Reset</button>*@
                <button type="reset" class="btn btn-default">Reset</button>
            </div>
        </div>
    </div>
</div> 

我知道这是一个老问题,但我会这样做。

如果您使用的是强类型视图模型,您可以添加一个名为IsModalShown的属性,即

public class Foo
{
    public bool IsModalShown { get; set; }
}

在您的视图中将其渲染为隐藏的,即

@Html.HiddenFor(m => m.IsModalShown)

当模态打开时,将隐藏值设置为true,这将使模态状态能够发布回控制器动作,即

$('#signin_modal').on('show.bs.modal', function (e) {
    $('#IsModalShown').val(true);
})

请注意,以上内容将取决于您使用的引导程序版本,但官方网站上还有其他文档

然后将以下内容添加到您的视图中,自动弹出

$(function(){
    @if(Model.IsModalShown)
    {
        $('#signin_modal').modal('show');
    }
});

弹出窗口中显示的其他字段也可以使用模型中的属性进行设置。