-3

I am passing ViewBag like,

 var forms = SqlMapper.Query(con, "getDetails", param, commandType: CommandType.StoredProcedure);

 ViewBag.myForm = forms;

This 'forms' contains values like VehicleType, VehicleName, VehiclePrice and I am displaying those in the view using loop,

  @foreach (var frm in ViewBag.myForm)
  {
  <div class="form-group">

  <label for="exampleInputEmail1">@frm.VehicleType</label>
  <label for="exampleInputEmail1">@frm.VehicleName</label>
  <label for="exampleInputEmail1">@frm.VehiclePrice</label>
  </div>
  }

This works fine. Now I want to display VehicleType in the header as well. And I don't want to loop the ViewBag again to get the VehicleType. VehicleType will be same for the list. Like if I get 'Car' as VehicleType, then for that ViewBag, 'Car' is the only VehicleType. How can I read VehicleType without looping ViewBag? Thanks

To get more idea on data,

Vehicle Type | Name | Price
Car          | Ford | 1000000
Car          | Audi | 1500000
Car          | Chev.| 1250000
Car          | Volks| 1246000

I want to display the Vehicle type,

 <div class="box-header with-border">
                        <h3 class="box-title">@ViewBag.myForm ----- VehicleType</h3>
                    </div>
Johny Bravo
  • 414
  • 9
  • 34

1 Answers1

2

You should use a model instead of ViewBag.That way you won't have to loop through the list to get one VehicleType

Vehicle.cs

public class Vehicle
{
    public int VehicleID {get; set;}
    public string VehicleType {get; set;}
    public string VehicleName {get; set;}
    public double VehiclePrice {get; set;}
}

Controller

var forms = SqlMapper.Query(con, "getDetails", param, commandType: CommandType.StoredProcedure);
List<Vehicle> vehicleList = new List<Vehicle>();
vehicleList = forms; 

View

    @model IEnumerable<ProjName.Models.Vehicle> 

    @Html.DisplayFor(model => model.ElementAt(0).VehicleType)
    @foreach (var frm in Model)
    {
    <div class="form-group">

        <label for="exampleInputEmail1">@frm.VehicleName</label>
        <label for="exampleInputEmail1">@frm.VehiclePrice</label>
    </div>
    }
Shawn Yan
  • 183
  • 8
  • Agreed on model approach. Just curious with ViewBag...Is it not possible? – Johny Bravo Jun 30 '16 at 05:07
  • 1
    It is possible but not encourage as ViewBag is more suitable to store temporary data. Once you do a redirection you will lost your ViewBag data as it is only available during the life-cycle of HTTP request.You can read [this](http://stackoverflow.com/questions/9186674/viewbag-viewdata-lifecycle) to get a better understanding. Cheers! :-) – Shawn Yan Jun 30 '16 at 06:24