asp.net - 将 ViewBag 结果绑定到 Html 下拉列表
问题描述
ASP.NET Core MVC 的新功能:尝试绑定 sql 查询的结果(在我的 Controller 上)并添加到 ViewBag 和 Html 下拉列表(下拉列表 B)。Action 方法是基于使用 Ajax 的另一个下拉列表(下拉列表 A)中的更改触发的。
View (if change in dropdown A):
$.ajax({
type: "POST",
url: "/Home/GetBrandsForDropdown",
data: null,
success: function (result) {
alert('Success')
},
error: function (req, status, error) {
alert('No Success')
}
});
Note: Alert is 'No Success" when I run it.
Controller:
public IActionResult GetBrandsForDropdown()
{
var content = from b in Context.Brands
select new { b.BrandNumber, b.BrandName };
ViewBag.BrandListing = content.Select(c => new SelectListItem
{
Text = c.BrandName,
Value = c.BrandNumber.ToString()
}).ToList();
return View();
}
Note: ViewBag.BrandListing includes values when I debug.
尝试将 ViewBag 中的值转换为以下内容但未成功:
<select class="dropdown form-control" onchange="getOption()" name="brandDDL"
id="ddlBrandName"style="background-color: #E6E6E6;
font-size: small; color: black; font-weight: bold;
border: double">
这似乎是应该很容易解决的问题,但我没有运气得到我想要的结果。
任何/所有帮助将不胜感激。杰克
解决方案
一个简单的方法是遍历 viewbag;
<select class="dropdown form-control" onchange="getOption()" name="brandDDL" id="ddlBrandName"style="background-color: #E6E6E6; font-size: small; color: black; font weight: bold; border: double">
@foreach(var item in ViewBag.BrandListing){
<option value="@item.Value">@item.Text</option>
}
</select>
推荐阅读
- php - pecl 更新:pear.php.net 正在使用不受支持的协议 - 这绝不应该发生
- java - 我想在链表之间找到数字
- sql - 在 oracle pl/sql 中添加半个月
- ios - iOS 共享表和复制选项粘贴链接在某些情况下不起作用
- javascript - 滑动检测(仅左右,不上下)
- php - IBM Cloud PHP 入门教程 - “php composer.phar install”出错
- javascript - JSZip 复制文件并在创建新 zip 时出错
- r - ggplot - 仅绘制颜色条
- html - 如何在 mat-card-image 的各个方面制作边距?
- protractor - 如何在 angular-cli 中为 e2e 指定不同的配置文件?