2012-07-11 60 views
0

我有这样的代码:硬编码的下拉菜单(用于创建和更新数据)

当您编辑的用户配置(与相应的CRUD(Controlers +查看)),你会看到一个下拉的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; } 
} 

我想要什么: 我想要一个简单的事情,但我不能设法做到这一点:

我想sextype被硬编码(男/女)在我的模型(或控制器)。 不在数据库中。 我不想要任何数据库,但每次创建或更新“UserProfile”上的记录时,只需用“男性/女性”选项可视化下拉菜单。

你能帮我吗?

+0

你的cshtml是什么样子? – 2012-07-11 17:12:45

+0

你要求性而不是性别的任何理由? – CodesInChaos 2012-07-11 18:14:48

回答

2

您可以在您的视图做到这一点:

@Html.DropDownList("SexType", 
    new[] { 
     new SelectListItem() { Text="Male", Value = "M" }, 
     new SelectListItem() { Text="Female", Value = "F" } 
    } 
); 
+0

你还应该添加一个“未指定/不愿意告诉”选项,并且可能还会添加一个“其他”选项。 – CodesInChaos 2012-07-11 18:49:41

+0

“Both”呢? – 2012-07-11 19:18:14

+0

我会将其包含在其他类别中。 – CodesInChaos 2012-07-11 19:48:23

0

添加一个新的属性,你UserProfile视图模型举行列表OT 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; } 
} 

而在你GET操作方法,可以填写它并返回到视图

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); 
} 

和你在r视图是强烈地约束到UserProfile ViewModel,

@Html.DropDownListFor(x => x.SexTypeId, new SelectList(Model.SexTypes, 
                "Value","Text"), "Select..") 
+0

感谢您的回复。我会尽快尝试。我只是想,我将不得不做一些编辑记录的进一步代码... – PnP 2012-07-12 18:46:55