我正在使用枚举来填充我的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())
尝试在你的控制器使用这个:'返回items.Distinct() ;' – Yoav
加入独特没有效果。我仍然在下拉列表中获取重复的选择文本值。 – Shawn