MVC剃刀格式使用groupby回发viewmodel

时间:2013-05-13 23:06:33

标签: c# asp.net-mvc razor

您好我有以下viewModel:

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语法,而不是因为我不知道如何编写和编辑状态。

任何人都可以帮我吗?

2 个答案:

答案 0 :(得分:1)

@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>    
     }
}

但是,我建议将您的列表分组到控制器中,而不是查看。

答案 1 :(得分:0)

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

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