且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 ASP.NET MVC5 中绑定 @Html.DropDownListFor 的***方法是什么?

更新时间:2023-02-24 23:29:36

强类型视图模型方法,不使用 ViewBag 之类的动态内容

您可以为类型为 SELECT 选项的视图模型添加一个新属性IEnumrable.

You can add a new property to your view model for the SELECT options of type IEnumrable<SelectListItem>.

视图模型是一个简单的 POCO 类,用于在视图和操作方法之间传输数据,反之亦然.它们特定于视图.添加视图所需的属性.

public class CreateUserVm
{
   public IEnumrable<SelectListItem> Labs { set;get;}
   public int SelectedLabId { set;get;}
   //Add other properties as needed for the view
}

并在您的 GET 操作中,创建此视图模型的对象,加载 Labs 属性并将其发送到视图.

and in your GET action, create an object of this view model, load the Labs property and send that to the view.

public ActionResult Create()
{
  var vm= new CreateUserVm();
  // Hard coded for demo. You can replace with real data from db
  vm.Labs = new List<SelectListItem> {
     new SelectListItem { Value="1", Text="One" },
     new SelectListItem { Value ="2", Text="Two" }
  };
  return View(vm);
}

并且在这个视图模型的强类型视图中,调用 DropDownListFor 辅助方法

and in the view which is strongly typed to this view model, call the DropDownListFor helper method

@model CreateUserVm
@Html.DropDownListFor(f=>f.SelectedLabId, Model.Labs,"Select one")

在下拉列表中预先选择一个选项

如果您想在 razor 渲染页面时预先选择一个选项,您可以将视图模型的 SelectedLabId 属性值设置为视图模型的 value 属性值选项(SelectListItem).

If you like to pre select one option when razor renders the page, You can set the SelectedLabId property value of your view model to the value property value of of the Option item(SelectListItem).

public ActionResult Create()
{
  var vm= new CreateUserVm();
  // Hard coded for demo. You can replace with real data from db
  vm.Labs = new List<SelectListItem> {
     new SelectListItem { Value="1", Text="SugarLab" },
     new SelectListItem { Value ="2", Text="CandyLab" },
     new SelectListItem { Value ="3", Text="SodaLab" }
  };
  vm.SelectedLabId = 2; // Will set "CandyLab" option as selected
  return View(vm);
}

如果你想使用真实数据,而不是硬编码的2项,你可以这样做

If you want to use real data, instead of the hard coded 2 items, you can do this

vm.Labs = dbContext.Labs.Select(x=>new SelectListItem { Value=x.Id.ToString(),
                                                        Text= x.Name }).ToList();

假设 dbContext 是您的 DbContext 类对象,并且它具有 DbSet 类型的 Labs 属性,其中每个 Lab 实体都有一个 Id和名称属性.

Assuming dbContext is your DbContext class object and it has a Labs property of type DbSet<Lab> where each Lab entity has an Id and Name property.