Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

c# - asp-for binding and route-value issues inside loop

I am building a little website where users can manage personal gear, which has a name and mass among other properties. I want to display all of this gear in a table, using input boxes bound to each item so the user can change values if desired, then hit an edit button and update the gear database. I can get my foreach loop to bind all of the right values, but when it routes to the handler, it always sets the EditGearName and EditGearMass value to whatever value is in the first row.

<table>
  @foreach (var g in Model.Gears) {
  <tr class="list-table-main">
    <td><input class="form-control" asp-for="EditGearName" value="@g.GearName" /></td>
    <td><input class="form-control" asp-for="EditGearMass" value="@g.Mass" type="number" min="0" /></td>
    <td style="width:12.5%"><button type="submit" asp-page-handler="EditGear" asp-route-groupid="@gg.ID">Save</button></td>
  </tr>
  }
</table>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

it always sets the EditGearName and EditGearMass value to whatever value is in the first row.

You should add the form tag in the foreach loop to enable one submit for one row.

<table>
    <form>
    @foreach (var g in Model.Gears) {
    <tr class="list-table-main">
        <td><input class="form-control" asp-for="EditGearName" value="@g.GearName" /></td>
        <td><input class="form-control" asp-for="EditGearMass" value="@g.Mass" type="number" min="0" /></td>
        <td style="width:12.5%"><button type="submit" asp-page-handler="EditGear" asp-route-groupid="@gg.ID">Save</button></td>
    </tr>
    }
    </form>
</table>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...