我看过类似的问题,找不到能帮助我的答案。我在我的模型方法中分配SelectListItem Selected属性。我看到模型进入视图并且它具有所选值。但是当它在视图中输出时,我只选择了第一个值。
型号:
public class ProductModel
{
public int ID { get; set; }
[Required(ErrorMessage = "Required")]
[Index("ItemNumber", 1, IsUnique = true)]
[Display(Name = "Item #")]
public int itemNumber { get; set; }
[Required(ErrorMessage = "Required")]
[Display(Name = "Product")]
[MaxLength(50)]
public String product { get; set; }
[Display(Name = "Description")]
[MaxLength(500)]
public String description { get; set; }
[DefaultValue(true)]
[Display(Name = "Active?")]
public bool active { get; set; }
[Display(Name = "Image Name")]
public String imageName { get; set; }
[Display(Name = "PDF Name")]
public String PDFName { get; set; }
[ForeignKey("Category")]
public int CategoryID { get; set; }
public virtual CategoryModel Category { get; set; }
public IEnumerable<SelectListItem> CategoryList { get; set; }
public static IEnumerable<SelectListItem> getCategories(int id = 0)
{
using (var db = new ProductContext())
{
List<SelectListItem> list = new List<SelectListItem>();
var x = db.Categories.ToList();
foreach (var y in x)
{
//SelectListItem sli = new SelectListItem { Value = y.ID.ToString(), Text = y.categoryName };
SelectListItem sli = new SelectListItem { Value = y.ID.ToString(), Text = y.categoryName };
if (id > 0 && y.ID == id)
{
sli.Selected = true;
}
list.Add(sli);
}
return list;
}
}
public ProductModel()
{
active = true;
}
}
控制器方法分配返回值:
public ActionResult EditProduct(int? id)
{
ProductModel model = new ProductModel();
if (id != null)
{
using (var db = new ProductContext())
{
if (id != 0)
{
model = db.Products.Find(id);
}
if (Session["dropdownID"] != null && Session["dropdownID"].ToString().Trim() != "")
{
int dropdownID = Int32.Parse(Session["dropdownID"].ToString());
model.CategoryList = ProductModel.getCategories(dropdownID);
}
else
{
model.CategoryList = ProductModel.getCategories();
}
}
}
return PartialView(model);
}
查看代码:
<div class="form-group">
@Html.LabelFor(model => model.Category, new { @class = "control-label col-md-8" })
<div class="col-md-16">
@Html.DropDownListFor(model => model.CategoryID, Model.CategoryList, new { @class = "form-control"})
@Html.ValidationMessageFor(model => model.CategoryID)
</div>
</div>
答案 0 :(得分:1)
我认为问题是列表项是由model => model.CategoryID
返回的值而不是项目本身的Selected属性选择的。因此,如果在显示视图时CategoryID == 0,则将选择列表中的第一个项目。根据我的经验,HTML帮助程序忽略了SelectListItem的Selected属性。