gpt4 book ai didi

c# - MVC 4 Simple Populate DropDown 从数据库模型

转载 作者:太空狗 更新时间:2023-10-29 18:04:03 25 4
gpt4 key购买 nike

我觉得有点傻。

我试图掌握 MVC 4 的窍门,使用装箱作为功能示例。

我在数据库中有 WeightCategories(Heavyweights 等)和 Boxers

看似简单。关系是一个拳击手有一个当前的体重类别,但当我编辑时,我希望它能够通过下拉菜单改变它。

如果它是我自己在代码中制作的列表,我知道该怎么做,但我无法理解如何从 WeightCategory 表中“加载”列表并将其显示在拳击手的 View /模型。

所以,这是我为 WeightCategory 项目编写的代码:

[Table("WeightCategories")]
public class WeightCategory
{
[Key]
public int WeightCategoryId { get; set; }

public WEIGHT_CATEGORIES WeightCategoryType { get; set; }

[Display(Name = "Weight Category Name")]
[Required]
[MinLength(5)]
public string Name { get; set; }
[Display(Name = "Weight Limit In Pounds")]
public int? WeightLimit { get; set; }
}

这是拳击手项目的代码

[Table("Boxers")]
public class Boxer
{
[Key]
public int BoxerId { get; set; }

public WeightCategory CurrentWeightCategory { get; set; }

[Required]
public string Name { get; set; }
public int Wins { get; set; }
public int Losses { get; set; }
public int Draws { get; set; }
public int Kayos { get; set; }
}

在 View 中,我真的不确定如何解决这个问题,我很确定它不是自动的,我可能需要将表加载到 Controller 中的某个位置......我正在寻找最佳实践或其他东西.

最后的 View 中类似的东西:

@Html.DropDownListFor(model => model.CurrentWeightCategory.WeightCategoryId,
new SelectList(Model.WeightCategories, "WeightCategoryId", "Name",
Model.WeightCategories.First().WeightCategoryId))

最佳答案

你可以设计一个 View 模型:

public class MyViewModel
{
public Boxer Boxer { get; set; }
public IEnumerable<SelectListItem> WeightCategories { get; set; }
}

然后让您的 Controller 操作填充并将此 View 模型传递给 View :

public ActionResult Edit(int id)
{
var model = new MyViewModel();
using (var db = new SomeDataContext())
{
// Get the boxer you would like to edit from the database
model.Boxer = db.Boxers.Single(x => x.BoxerId == id);

// Here you are selecting all the available weight categroies
// from the database and projecting them to the IEnumerable<SelectListItem>
model.WeightCategories = db.WeightCategories.ToList().Select(x => new SelectListItem
{
Value = x.WeightCategoryId.ToString(),
Text = x.Name
})
}
return View(model);
}

现在你的 View 变成了 View 模型的强类型:

@model MyViewModel
@Html.DropDownListFor(
x => model.Boxer.CurrentWeightCategory.WeightCategoryId,
Model.WeightCategories
)

关于c# - MVC 4 Simple Populate DropDown 从数据库模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14304331/

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