Bootstrap 4中LoginView控件渲染嵌套<a>标签问题求助
I’ve run into this exact issue before—Bootstrap 4’s dropdown structure changes catch a lot of folks off guard when working with ASP.NET’s LoginView control. Let’s break down why this happens and how to fix it:
The Root Problem
In Bootstrap 3, dropdown items use a <ul><li><a>...</a></li></ul> structure. Your LoginView’s rendered <a> tag sits neatly inside the <li>—no nesting issues, since HTML standards prohibit <a> tags containing other <a> tags.
But Bootstrap 4 uses <a class="dropdown-item">...</a> directly for dropdown links. When your LoginView renders its own <a> tag inside this, you end up with invalid nested <a> elements:
<a class="dropdown-item"> <a href="/Account/Login">Login</a> <!-- Invalid nested <a>! --> </a>
This breaks HTML validity and can cause weird behavior with clicks or styling.
Solution 1: Use a <button> for the Dropdown Item
Bootstrap 4 fully supports using <button> elements with the dropdown-item class. Swap out the outer <a> for a button, and let LoginView render its <a> inside it—this avoids nested links entirely:
<div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> User Menu </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <!-- Use button instead of a for dropdown-item --> <button class="dropdown-item" type="button"> <asp:LoginView runat="server"> <AnonymousTemplate> <a href="~/Account/Login">Login</a> </AnonymousTemplate> <LoggedInTemplate> <a href="~/Account/Manage">Hello, <%= Page.User.Identity.Name %></a> </LoggedInTemplate> </asp:LoginView> </button> </div> </div>
The button will inherit all the dropdown-item styling, and the nested <a> from LoginView will work as expected without validity issues.
Solution 2: Move the Dropdown Item <a> Outside LoginView
If you prefer to keep using an <a> for the dropdown item, adjust your LoginView to only render text (not the <a> tag), and handle the link logic in the outer dropdown-item:
<div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> User Menu </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" href='<%# LoginView1.LoggedIn ? "~/Account/Manage" : "~/Account/Login" %>'> <asp:LoginView runat="server" ID="LoginView1"> <AnonymousTemplate>Login</AnonymousTemplate> <LoggedInTemplate>Hello, <%= Page.User.Identity.Name %></LoggedInTemplate> </asp:LoginView> </a> </div> </div>
Here, the outer <a class="dropdown-item"> handles the link destination, and LoginView just outputs the appropriate text. No nested links, and full Bootstrap styling remains intact.
Either approach will fix the invalid HTML structure and get your dropdown working as intended with LoginView.
内容的提问来源于stack exchange,提问作者user8142888

