我有一个使用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; }
...
}
OfferCategory:
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 Action:
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(商品报价)处理程序没有获得在表单中选择的OfferCategory。我怎么能让它工作?
答案 0 :(得分:0)
你有这个:
<div class="editor-label">
@Html.LabelFor(model => model.OfferCategory)
</div>
<div class="editor-field">
@Html.DropDownListFor(model=>model.OfferCategory, (IEnumerable<SelectListItem>)ViewBag.OfferCategories)
</div>
您需要更改为
<div class="editor-label">
@Html.LabelFor(model => model.OfferCategory)
</div>
<div class="editor-field">
@Html.DropDownListFor(model=>model.OfferCategory.Id, (IEnumerable<SelectListItem>)ViewBag.OfferCategories)
</div>
注意model =&gt; model.OfferCategory.Id而不是model =&gt; model.OfferCategory
答案 1 :(得分:-1)
您的问题是您在下拉列表“model =&gt; model.OfferCategory”中指定,它会生成接近'select name =“model.OfferCategory”'的html。当表单被发布到您的操作“AddOffer(商品报价)”时,asp.net mvc模型绑定器尝试创建OfferCategory对象,但它不能这样做因为它所知道的只是一个类别ID。你需要做的是改变你的下拉列表方式,以便: @ Html.DropDownListFor(型号=&GT; model.OfferCategory.Id,(IEnumerable的)ViewBag.OfferCategories)。完成后,您将获得使用Id属性填充创建的OfferCategory对象。 我希望这会对你有所帮助。