0

我有这个代码:

当您编辑 UserProfile(使用相应的 CRUD(控制器 + 视图))时,您将看到 SexType 的下拉列表(您也可以使用其他一些 CRUD 进行编辑),并将对应于 SexType 表。

public class UserProfile{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int SexTypeId { get; set; }
public virtual SexType SexType { get; set; }

public class SexType
{
    public int SexTypeId { get; set; }
    public string SexTypeDescription { get; set; }
    public virtual ICollection<UserProfile> UserProfiles { get; set; }
}

 public class UserProfileDBContext : DbContext //This creates the database according to the model
{
    public DbSet<UserProfile> UserProfiles { get; set; }
    public DbSet<SexType> SexType { get; set; }
}

我想要什么:我想要一个更简单的东西,但我做不到:

我希望在我的模型(或控制器)上对性别类型进行硬编码(男性/女性)。不在数据库中。我不想要任何数据库,而只是在每次创建或更新“UserProfile”上的记录时使用“男性/女性”选项可视化一个下拉列表。

你能帮我解决这个问题吗?

4

2 回答 2

2

您可以在您的视图中执行此操作:

@Html.DropDownList("SexType", 
    new[] { 
        new SelectListItem() { Text="Male", Value = "M" },  
        new SelectListItem() { Text="Female", Value = "F" }
    }
);
于 2012-07-11T17:50:42.787 回答
0

向 ViewModel 添加一个新属性以UserProfile保存 SexTypes 列表

public class UserProfile{
  public int Id { get; set; }
  public string Name { get; set; }
  public string Surname { get; set; }
  public int SexTypeId { get; set; }
  public IEnumerable<SelectListItem> SexTypes { get; set; }
}

在你的GETAction 方法中,你可以填充它并返回到 View

public ActionResult Create()
{
  var model=new UserProfile();
  model.SexTypes = new[]
  {
     new SelectListItem { Value = "M", Text = "Male" },
     new SelectListItem { Value = "F", Text = "FeMale" },         
  }; 
  return View(model);
}

UserProfile并且在您与ViewModel紧密绑定的视图中,

@Html.DropDownListFor(x => x.SexTypeId, new SelectList(Model.SexTypes,
                                                  "Value","Text"), "Select..")
于 2012-07-11T17:57:08.927 回答