我正在使用枚举来填充我的DropDownList,它可以正常使用List和Create视图,但我的Edit视图会在DropDownList中加载重复值。重复值只是属性的选定值,如果Rented是保存在数据库中的值,DropDownList将显示已选中Rented,Available和列表中的另一个Rented。我需要知道的是如何加载一个DropDownList,它选择以前存储在DB中的PropertyStatus枚举的值,而没有任何重复项?
的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 :(得分: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)