2012-11-11 91 views
0

我正在使用枚举来填充我的DropDownList,它可以与List和Create views正常工作,但是我的Edit视图会在DropDownList中加载重复的值。重复值只是属性含义的选定值,如果“已租用”是保存在数据库中的值,则DropDownList将在列表中显示已选择的已租用,可用和已租用的另一个值。我需要知道的是如何加载一个DropDownList,它选择以前存储在数据库中的PropertyStatus枚举值,而不会有任何重复项?MVC 3 DropDownList在编辑页面上显示多个值

的Controler:

 public ActionResult Edit(int id) 
    { 
     Property property = db.Properties.Find(id); 

     ViewBag.PropertyStatus = SetViewBagPropertyStatus(); 
     return View(property); 
    } 

    private IEnumerable<SelectListItem> SetViewBagPropertyStatus() 
    { 
     IEnumerable<ePropStatus> values = 
      Enum.GetValues(typeof(ePropStatus)).Cast<ePropStatus>(); 

      IEnumerable<SelectListItem> items = 
      from value in values 
      select new SelectListItem 
      { 
       Text = value.ToString(), 
       Value = value.ToString() 
      }; 
      return items; 
    } 

型号:

public enum ePropStatus 
    { 
     Available , 
     Rented 
    } 

    public partial class Property 
    { 
     public int PropertyId { get; set; } 
     public string PropName { get; set; } 
     public string Address { get; set; } 
     public string City { get; set; } 
     public string State { get; set; } 
     public string ZipCode { get; set; } 
     public int SqFeet { get; set; } 
     public int Bedrooms { get; set; } 
     public int Bathrooms { get; set; } 
     public int Garage { get; set; } 
     public string Notes { get; set; } 
     public ePropStatus PropertyStatus { get; set; } 
    } 

编辑观点:

@Html.DropDownList("PropertyStatus", Model.PropertyStatus.ToString()) 
+0

尝试在你的控制器使用这个:'返回items.Distinct() ;' – Yoav

+0

加入独特没有效果。我仍然在下拉列表中获取重复的选择文本值。 – Shawn

回答

0

试试这个:

@Html.DropDownListFor(model => model.PropertyStatus, ViewBag.PropertyStatus) 

编辑:::或者试试这个

的Controler:

public ActionResult Edit(int id) 
{ 
    Property property = db.Properties.Find(id); 

    ViewBag.PropertyStatusList = SetViewBagPropertyStatus(property.PropertyStatus); 
    return View(property); 
} 

private IEnumerable<SelectListItem> SetViewBagPropertyStatus(string selectedValue = "") 
{ 
    IEnumerable<ePropStatus> values = 
     Enum.GetValues(typeof(ePropStatus)).Cast<ePropStatus>(); 

     IEnumerable<SelectListItem> items = 
     from value in values 
     select new SelectListItem 
     { 
      Text = value.ToString(), 
      Value = value.ToString(), 
      Selected = (selectedValue == value.ToString()) 
     }; 
     return items; 
} 

查看:

@Html.DropDownList("PropertyStatus", ViewBag.PropertyStatusList) 
+0

不幸的是,这并没有工作我得到Model.Property没有适用的方法DropDownListFor但似乎有一个名称的扩展方法。扩展方法不能动态分派。 – Shawn

+0

@Shawn,我已经更新了我的答案看看 –

+0

我已经尝试使用@ Html.DropDownList(“PropertyStatus”,ViewBag.PropertyStatusList),但它仍然返回相同的异常。 – Shawn

相关问题