Project on ASP NET Core MVC 3.1, jQuery v3.5.1, Bootstrap v4.1.3.
Case - get drop down list items based on user role. Drop down component from Bootstrap 4.
What works:
<a>
with asp-controller=Profile
and asp-action=Admin
tags.What does not work:
jQuery code which I use to create <a>
elements in <div>
drop-down:
<script>
$(document).ready(function () {
$('#dropdownMenuLink').on('click', function () {
GetDropDownMenu();
});
});
function GetDropDownMenu() {
$.ajax({
type: "GET",
url: "/Menu/GetProfileMenu",
success: function (response) {
console.log(response);
var menuDiv = $(".dropdown-menu");
$.each(response, function (i, element) {
console.log(element);
var controllerAndAction = element.path.split('/');
var aElement = $('<a>').attr({ 'asp-controller': controllerAndAction[0], 'asp-action': controllerAndAction[1], 'class':"dropdown-item" });
aElement.text(element.text);
menuDiv.append(aElement);
});
}
});
}
</script>
Html drop down element:
<div class="dropdown">
<a class="btn btn-secondary dropdown-toggle" href="#" role="button" id="dropdownMenuLink"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Profile
</a>
<div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
</div>
</div>
I don't think you can set the asp-* properties after rendering like that.
Instead just set the href attribute of the link.
<script>
$(document).ready(function () {
$('#dropdownMenuLink').on('click', function () {
GetDropDownMenu();
});
});
function GetDropDownMenu() {
$.ajax({
type: "GET",
url: "/Menu/GetProfileMenu",
success: function (response) {
console.log(response);
var menuDiv = $(".dropdown-menu");
$.each(response, function (i, element) {
console.log(element);
var controllerAndAction = element.path.split('/');
//set href however you want
var aElement = $('<a>').attr({ 'href': "/" + controllerAndAction[0] + "/"+ controllerAndAction[1], 'class':"dropdown-item" });
aElement.text(element.text);
menuDiv.append(aElement);
});
}
});
}
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.