Display Bootstrap Modal from Asp.Net Webforms

空扰寡人 提交于 2019-11-28 06:29:44

First of all, I suggest you put your Modal in an UpdatePanel and set the Title and Body from CodeBehind. By this trick, you don't need to create a separate Modal for each button or each message. So I modify your code and add an UpdatePanel:

<div class="container">
    <div class="btn-group">
        <asp:Button ID="btnSubmit" class="btn-info" runat="server" Text="Submit"          
        OnClick="btnSubmit_Click"></asp:Button>
    </div>
</div>


<!-- Bootstrap Modal Dialog -->
<div class="modal fade" id="myModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <asp:UpdatePanel ID="upModal" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
            <ContentTemplate>
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title"><asp:Label ID="lblModalTitle" runat="server" Text=""></asp:Label></h4>
                    </div>
                    <div class="modal-body">
                        <asp:Label ID="lblModalBody" runat="server" Text=""></asp:Label>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-info" data-dismiss="modal" aria-hidden="true">Close</button>
                    </div>
                </div>
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
</div>


and in CodeBehind:

protected void btnSubmit_Click(object sender, EventArgs e)
{
    lblModalTitle.Text = "Validation Errors List for HP7 Citation";
    lblModalBody.Text = "This is modal body";
    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myModal", "$('#myModal').modal();", true);
    upModal.Update();
}

First, we set the Modal's Title and Body, then display it, and finally update the UpdatePanel.

A good practice to improve the page's loading speed is putting the Modal code at the end of the page, besides this helps you avoid any conflict with other UpdatePanels or elements.
A more advanced and tricky suggestion: Put the Modal code at the end of your MasterPage and write a global function to update it, and make your life even easier!

Troubleshooting:
If you get the Error: Object doesn't support property or method 'modal', a likely reason could be failing setup of Bootstrap, try to check your code with the official bootstrap sample: http://getbootstrap.com/javascript/#modals
If you still get the error, maybe you find these links helpful:
http://geekswithblogs.net/JeremyMorgan/archive/2012/09/18/how-to-use-twitter-bootstrap-on-an-asp.net-website.aspx
http://www.mytecbits.com/microsoft/dot-net/bootstrap-3-0-0-with-asp-net-web-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!