gpt4 book ai didi

c# MVC - 从类属性填充 DropDownList

转载 作者:行者123 更新时间:2023-11-30 23:24:03 24 4
gpt4 key购买 nike

我正在使用 EF 和 MVC,这对我来说是新事物。我有以下类(class):

 public class Client
{
[Key]
public int ClientId { get; set; }
public Category Category { get; set; }

}

我想在与“创建”ActionResult 相关的 View 中显示一个可选择的 DropDownList,其中包含可供选择的所有类别。

我还有一个 ViewModel:

public class CategoryViewModel
{
public int SelectedCategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}

我在 Controller 中使用:

private IEnumerable<SelectListItem> GetCategories()
{
var db = new MyDBContext();
var categories = db.Categories
.Select(x =>
new Category
{
CategoryId = x.CategoryId,
Name = x.Name
});

return new SelectList(categories, "Value", "Text");
}

...并在 Create() 中:

public ActionResult Create()
{
var model = new CategoryViewModel();
model.Categories = GetCategories();
return View(model);
}

我不知道如何填充 View 中的下拉列表:

<div class="form-group">
@Html.LabelFor(model => model.Category, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(WHAT GOES HERE????)

</div>
</div>

谢谢你救了我! (RE5 报价)

最佳答案

有不同的overloads但这是一个选项:

@Html.DropDownListFor(x => x.SelectedCategoryId, Model.Categories)

关于c# MVC - 从类属性填充 DropDownList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38034294/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com