Razor,用于ICollection属性的TextBoxFor
//产品Razor,用于ICollection属性的TextBoxFor,razor,asp.net-mvc-4,Razor,Asp.net Mvc 4,//产品 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 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; }
}
我喜欢上面的实体表,我想为更新产品页面中的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.TextBoxForModel.Pricing=>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属性绘制文本框?我建议您使用编辑器模板 因此,只需在控制器中初始化定价集合,然后将其完成为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);
简单。无需担心循环,无需担心索引,ASP.NET MVC框架将处理所有问题。您只需遵循内置的约定即可。我建议您使用编辑器模板 因此,只需在控制器中初始化定价集合,然后将其完成为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);
简单。无需担心循环,无需担心索引,ASP.NET MVC框架将处理所有问题。您只需遵循内置的约定即可。Wow!令人惊叹的非常感谢你!哇!令人惊叹的非常感谢你!
@model BrownieDAL.Entities.Product
<table>
<thead>
<tr>
<th>Price / Order Qty</th>
</tr>
</thead>
<tbody>
@Html.EditorFor(model => model.Pricing)
</tbody>
</table>
@model BrownieDAL.Entities.Pricing
<tr>
<td>
@Html.TextBoxFor(model => model.Price)
@Html.TextBoxFor(model => model.OrderQty)
</td>
</tr>