MVC剃刀格式使用groupby回发视图模型

本文关键字:视图 模型 groupby 剃刀 格式 MVC | 更新日期: 2023-09-27 18:13:37

嗨,我有以下视图模型:

public class VehiclesViewModel
    {
        public IList<Vehicle> Vehicles{ get; set; }
    }

车辆为:

public class Vehicle
{
  public Owner Owner { get; set; }
  public Make Make { get; set; }
  public string Status { get; set; }
}

现在在剃刀视图中:

    @model VehiclesViewModel
    <table>
      <thead>
        <tr>
          <th>Owner</th>
          <th>Make</th>
          <th>Model</th>
        </tr>
      </thead>
      <tbody>
    @for(int i=0; i<Model.Vehicles.Count; i++)
    {
        <tr>
          <td>@Vehicle[i].Owner</td>
          <td>@Vehicle[i].Make</td>
          <td>@Html.EditorFor(x => x.Vehicles[i].Status)</td>
        </tr>
    }
    </tbody>
</table>

所以现在我有了一个视图,我可以显示和更改车辆的状态,并将其发布回控制器,没有问题。

然而,我现在有一个新的要求,即在按车主分组的页面上显示车辆。所以我想出了:

@model VehiclesViewModel
<table>
  <thead>
    <tr>
      <th>Make</th>
      <th>Model</th>
    </tr>
  </thead>
  <tbody>
@foreach(var vehicleGroup in @Model.Vehicles.GroupBy(x => x.Owner.Name))
{
  <tr>
     <td colspan="2">@vehicleGroup.First().Owner.Name</td>
  </tr>
  foreach(var vehicle in vehicleGroup)
  {
       <tr>
         <td>@vehicle.Make.Name</td>
         <td>Need to provide a way to edit the status here</td>
       </tr>
  }
}
</tbody>
</table>

问题是,现在我有了foreach语法,而不是for。我不知道如何编写和编辑状态。

有人能帮我吗?

MVC剃刀格式使用groupby回发视图模型

@foreach(var vehicleGroup in Model.Vehicles.GroupBy(x => x.Owner.Name))
{
    <tr>
        <td colspan="2">@vehicleGroup.First().Owner.Name</td>
    </tr>
     foreach(var vehicle in vehicleGroup)
     {
         <tr>
              <td> @vehicle.Make.Name  </td>
              <td> @Html.EditorFor(m => vehicle.Status) </td>
         </tr>    
     }
}

不过,我建议您在控制器中对列表进行分组,而不是查看。

也许只需要使用一个简单的输入标签:

<input type="text" name="vehicle-@vehicle.Id"value="@vehicle.Status" />