我有一个使用 Razor 的 ASP.NET MVC3 项目。我有下一个实体:
提供:
public class Offer
{
public Int32 Id { get; set; }
public String Name { get; set; }
public DateTime Added { get; set; }
public String Description { get; set; }
public Decimal Price { get; set; }
public String Address { get; set; }
public virtual OfferCategory OfferCategory { get; set; }
...
}
报价类别:
public class OfferCategory
{
public Int32 Id { get; set; }
public String Name { get; set; }
public String Description { get; set; }
public virtual List<Offer> Offers { get; set; }
...
}
我正在尝试使用 DropDownListFor(OfferCategory) 制作用于添加新优惠的表格。在这个 dropDownList 中将出现 db 中所有现有的 offerCategories。我在这里能走多远:
控制器中的 AddOffer 操作:
var categories = _context.OfferCategory.ToList();
List<SelectListItem> OfferCategories = new List<SelectListItem>();
foreach (var offerCategory in categories)
{
OfferCategories.Add(new SelectListItem() { Selected = false, Text = offerCategory.Name, Value = offerCategory.Id.ToString()});
}
ViewBag.OfferCategories = OfferCategories;
这是视图:
//... A lot of things
<div class="editor-label">
@Html.LabelFor(model => model.OfferCategory)
</div>
<div class="editor-field">
@Html.DropDownListFor(model=>model.OfferCategory, (IEnumerable<SelectListItem>)ViewBag.OfferCategories)
</div>
//... A lot of things
当表单中出现所有 OfferCategories 时,但是当我单击提交按钮时,我的 POST AddOffer(Offer offer) 处理程序没有获得表单中选择的 OfferCategory。我怎样才能使它工作?