如何重用 HTML 属性值

How can I reuse HTML attribute values

在下面的代码中,我在 Html.EditorFor() 方法中复制了 min = 0, max = 99 值。 让这个更干的最好方法是什么?

<div id="Team1PlayerScores">
    @for (int i = 0; i < Model.Team1.Players.Count; i++)
    {
        @Html.DisplayFor(m => Model.Team1.Players[i].Name)
        @Html.EditorFor(m => Model.Team1.Players[i].GoalsForCurrentGame, new { htmlAttributes = new { min = 0, max = 99, onchange = "updateTeamScore('Team1PlayerScores', 'Team1_GoalsForCurrentGame')" } })
    }
</div>

<div id="Team2PlayerScores">
    @for (int i = 0; i < Model.Team2.Players.Count; i++)
    {
        @Html.DisplayFor(m => Model.Team2.Players[i].Name)
        @Html.EditorFor(m => Model.Team2.Players[i].GoalsForCurrentGame, new { htmlAttributes = new { min = 0, max = 99, onchange = "updateTeamScore('Team2PlayerScores', 'Team2_GoalsForCurrentGame')" } })
    }
</div>

如果您的目的是删除代码中 "magic numbers" 的重复,而不是在生成的 HTML 中,您可以用模型中的值替换数字:

public class IndexModel
{
    public Team Team1 { get; set; }
    public Team Team2 { get; set; }

    public int MinimumGoals => 0;
    public int MaximumGoals => 99;
}

并更新视图以利用它:

<div id="Team1PlayerScores">
    @for (int i = 0; i < Model.Team1.Players.Count; i++)
    {
        @Html.DisplayFor(m => Model.Team1.Players[i].Name)
        @Html.EditorFor(m => Model.Team1.Players[i].GoalsForCurrentGame, 
         new { htmlAttributes = new { min = Model.MinimumGoals, max = Model.MaximumGoals, 
         onchange = "updateTeamScore('Team1PlayerScores', 'Team1_GoalsForCurrentGame')" } })
    }
</div>

<div id="Team2PlayerScores">
    @for (int i = 0; i < Model.Team2.Players.Count; i++)
    {
        @Html.DisplayFor(m => Model.Team2.Players[i].Name)
        @Html.EditorFor(m => Model.Team2.Players[i].GoalsForCurrentGame, 
         new { htmlAttributes = new { min = Model.MinimumGoals, max = Model.MaximumGoals,
         onchange = "updateTeamScore('Team2PlayerScores', 'Team2_GoalsForCurrentGame')" } })
    }
</div>

我已将这些值作为只读属性删除,但如何将它们实现到模型中取决于您。