[英]ASP.NET Core MVC link added by jQuery does not work
Project on ASP NET Core MVC 3.1, jQuery v3.5.1, Bootstrap v4.1.3. 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. Bootstrap 4 中的下拉组件。
What works:什么工作:
<a>
with asp-controller=Profile
and asp-action=Admin
tags.添加带有asp-controller=Profile
和asp-action=Admin
标签的<a>
。What does not work:什么不起作用:
jQuery code which I use to create <a>
elements in <div>
drop-down:我用来在<div>
下拉列表中创建<a>
元素的 jQuery 代码:
<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: Html 下拉元素:
<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.我不认为你可以在渲染后设置 asp-* 属性。
Instead just set the href attribute of the link.而只是设置链接的 href 属性。
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.