//产品
public class Product
{
[Key]
public int ID {get; set;}
public string PK {get; set;}
[Required(ErrorMessage="Category is required field.")]
public int CategoryID { get; set; }
[Required]
public string Title {get; set;}
public virtual ICollection<Pricing> Pricing { get; set; }
}
//定价
public class Pricing
{
[Key]
public int ID {get; set;}
public int ProductID {get; set;}
public decimal Price {get; set;}
public int OrderQty {get; set;}
public string PK { get; set; }
}
我喜欢上面的实体表,我想在更新产品页面中为ICollection 绘制 5文本框。但我不知道,我该怎么做。
@model BrownieDAL.Entities.Product
<th> Price / Order Qty</th>
<td>
@{int priceCnt = 0;}
@foreach(var price in Model.Pricing){
priceCnt++;
@Html.TextBoxFor(model => price.Price)
@Html.TextBoxFor(model => price.OrderQty)
<br />
}
@if (priceCnt < 5)
{
// ???
@Html.TextBoxFor(Model.Pricing => Model.Pricing.Price)
priceCnt++;
}
</td>
当我尝试使用'@ Html.TextBoxFor(Model.Pricing =&gt; Model.Pricing.Price)'时,我收到一条错误消息:
Error 1 'System.Collections.Generic.ICollection<PJ.Entities.Pricing>' does not contain a definition for 'Price' and no extension method 'Price' accepting a first argument of type 'System.Collections.Generic.ICollection<PJ.Entities.Pricing>' could be found (are you missing a using directive or an assembly reference?)
任何人都知道,我该如何为ICollection&lt;&gt;绘制文本框?属性?
答案 0 :(得分:3)
我建议您使用编辑器模板。
只需初始化控制器中的Pricing
集合,然后将其完成为5个元素:
model.Pricing = ... go get the pricing collection from wherever you were getting it previously
int count = model.Pricing.Count();
if (count < 5)
{
// we have less than 5 elements in the collection => let's complete it
// with empty Pricing elements:
var emptyItems = Enumerable.Range(1, 5 - count).Select(x => new Pricing());
model.Pricing = model.Pricing.Concat(emptyItems).ToList();
}
return View(model);
然后在你的视图中简单地说:
@model BrownieDAL.Entities.Product
<table>
<thead>
<tr>
<th>Price / Order Qty</th>
</tr>
</thead>
<tbody>
@Html.EditorFor(model => model.Pricing)
</tbody>
</table>
然后只需为Pricing
模型定义自定义编辑器模板(~/Views/Shared/EditorTemplates/Pricing.cshtml
):
@model BrownieDAL.Entities.Pricing
<tr>
<td>
@Html.TextBoxFor(model => model.Price)
@Html.TextBoxFor(model => model.OrderQty)
</td>
</tr>
简单。无需担心循环,无需担心索引,ASP.NET MVC框架将照顾一切。您需要做的就是遵循内置的约定。