[英]ASP.NET Core -> Label asp-for not returning label text
[英]ASP.NET Core MVC: asp-for is rendering incomplete id and name attributes
当我遍历 my.cshtml 文件中的列表时,由于某种原因,id 和 name 属性值呈现不完整。 例如:
@for (int i = 0; i < Model.product.ProductDetail.Count(); i++)
{
<input type="text"
asp-for="product.ProductDetail.ElementAt(i).Sku"
class="form-control"
placeholder="@SharedLocalizer["Sku"]" />
}
呈现为:
<input type="text" class="form-control" placeholder="Sku" id="Sku" name="Sku">
代替:
<input type="text" id="product.ProductDetail_0__Sku" name="product.ProductDetail[0].Sku" class="form-control" placeholder="Sku">
我正在使用 Entity Framework Core 3.1.3,这是我的 model:
产品:
public partial class Product
{
public Product()
{
ProductDetail = new HashSet<ProductDetail>();
}
/* More properties here... */
public virtual ICollection<ProductDetail> ProductDetail { get; set; }
}
产品明细:
public partial class ProductDetail
{
/* More properties here... */
public string Sku { get; set; }
}
产品视图型号:
public class ProductViewModel
{
public Product product { get; set; }
/* More properties here... */
}
你知道为什么会这样吗?
asp-for
是一个ModelExpression
,它被评估以构建id
和name
属性。 如果您使用ElementAt()
,则无法完全评估此表达式。
尝试在您的集合中使用直接索引器。 示例如下:
<input type="text"
asp-for="product.ProductDetail[i].Sku"
class="form-control"
placeholder="@SharedLocalizer["Sku"]" />
编辑:我强烈建议在您的视图中使用视图模型而不是数据持久性级别模型。 然后,您可以在视图 model 中使用List
(而不是ICollection
并相应地应用上述索引。
首先,使用asp-for="product.ProductDetail[i].Sku"
作为 CalC 共享可以对我测试 model 数据有用。
如果它确实不适合您,您可以尝试为您的输入字段手动设置 id、name 和 value 属性,如下所示。
这是我的 Model 代码:
产品:
public class Products
{
public Product product { get; set; }
}
产品:
public class Product
{
public List<ProductDetail> ProductDetail { get; set; }
}
产品明细:
public class ProductDetail
{
public string Sku { get; set; }
}
看法:
<div>
@for (int i = 0; i < Model.product.ProductDetail.Count(); i++)
{
<input type="text"
asp-for="product.ProductDetail[i].Sku"
class="form-control"
placeholder="@SharedLocalizer["Sku"]"/>
}
@for (int i = 0; i < Model.product.ProductDetail.Count(); i++)
{
<input type="text"
id="product_ProductDetail_@(i)__Sku"
name="product.ProductDetail[@(i)].Sku"
value="@Model.product.ProductDetail.ElementAt(i).Sku"
class="form-control"
placeholder="@SharedLocalizer["Sku"]"/>
}
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.