是否可以在 DropDownList html 助手中使用链接?



我有一个名为 category 的模型类,它从数据库中检索数据:

public class HomeController : Controller
{
private StoreContext db;
public HomeController()
{
db = new StoreContext();
}
public ActionResult Categories()
{
return View(db.Categories.ToList());
}
}

我想使用DropDownList辅助方法在视图中显示它们,并且我希望其中的所有类别都clickable,例如,当您单击它们时,它必须将您定位到属于单击类别的指定url。有没有办法通过DropDownList助手做到这一点?如果是,那如何?

你可以这样做,但你必须使用Jquery.如果你问怎么做?

例如:

我的示例实体

public class Category
{
public int Id { get; set; } 
public string Url{ get; set; } 
public string Name { get; set; } 
}

我的操作:

public IActionResult Categories()
{
var list = new List<Category>();
for (int i = 0; i < 10; i++)
{
list.Add(new Category(){Id = i, Url = "https://stackoverflow.com", Name = "stackoverflow" });
}
var selectList = list.Select(x => new SelectListItem() {Value = Url, Text = x.Name})
.ToList();
return View(selectList);
}

在我看来:

@Html.DropDownList("url",Model, "Choose a URL",  new { id = "url_list" })

然后使用 jQuery,您可以订阅此下拉列表的更改事件并导航到相应的 URL:

$(function() {
$('#url_list').change(function() {
var url = $(this).val();
if (url != null && url != '') {
window.location.href = url;
}
});
});

最新更新