【问题标题】:Razor Pages - Create unique identifier for controls in foreach loopRazor Pages - 为 foreach 循环中的控件创建唯一标识符
【发布时间】:2019-12-28 21:50:55
【问题描述】:

如何在使用 foreach 循环时为一组复选框创建唯一的名称引用?

@foreach (var item in Model.myClass.Where(i => i.ID1 == 0))
{
  <input type="text" asp-for="@item.Stuff" />
  <input type="text" asp-for="@item.Stuff" />
  <input type="text" asp-for="@item.Stuff" />
}

HTML(输出)

<input type="checkbox" checked="checked" id="item_Stuff" name="item_Stuff">
<input type="checkbox" checked="checked" id="item_Stuff" name="item_Stuff">
<input type="checkbox" checked="checked" id="item_Stuff" name="item_Stuff">

我已经看到 Razor Pages 推荐 here 但是这建议使用 for 循环或显式索引,这在我的情况下不起作用,因为我的语句中需要 where 子句。

示例

@for (var i = 0; i < 5; i++)
{
  <tr>
    <td>
      <input type="text" asp-for="Contacts[i].FirstName" />
    </td>
    <td>
      <input type="text" asp-for="Contacts[i].LastName" />
    </td>
    <td>
      <input type="text" asp-for="Contacts[i].Email" />
    </td>
  </tr>
}

【问题讨论】:

  • 您可以尝试使用 htmlhelpers 而不是标签助手,即使使用 foreach 您也可以使用整数计数器毫无问题地生成它们。
  • @{var i=0;} @foreach(var item in collection){++i;}看看我是如何使用这种 html 方式而不是使用标签助手
  • @Alok 谢谢。实际上,我已经可以使用标准 html 实现我需要的东西了在这种情况下,您是否建议不要使用标签助手?
  • 即使你可以做一些扩展,花这么多时间在 html 中已经可用的简单东西上是不值得的,另外,如果你使用直接 html,你知道事情不会变得复杂,它也会节省你的性能asp标签需要转换成html页面输出
  • @Alok 我认为你是对的。感谢您的洞察力。

标签: c# asp.net-core foreach .net-core razor-pages


【解决方案1】:

当您有在内容页面或视图中放置计数器变量的冲动时,这表明您正在做一些次优的事情。这是一种代码味道。

为了最小化 .cshtml 文件中的代码,我会做的是过滤 PageModel 中的项目。我会添加另一个属性:

public class MyPageModel : PageModel
{
    public List<MyClass> Entities { get; set; } = new List<MyClass>();
    public List<MyClass> EntitiesWithNoId => Entities.Where(e => e.ID == 0);
    // blah blah
}

然后在内容页面中:

@for (var i = 0; i < Model.EntitiesWithNoId.Count(); i++)
{
  <tr>
    <td>
      <input type="text" asp-for="EntitiesWithNoId[i].FirstName" />
    </td>
    <td>
      <input type="text" asp-for="EntitiesWithNoId[i].LastName" />
    </td>
    <td>
      <input type="text" asp-for="EntitiesWithNoId[i].Email" />
    </td>
  </tr>
}

这是一个利用 PageModel 的 ViewModel 方面的例子。它的部分作用是充当为视图准备数据的地方。

【讨论】:

    猜你喜欢
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多