简体   繁体   中英

ViewModel in ASP.NET MVC in detail view

I have a class name Flight . And I want to use this class ( flight ) with an extra field called count . I created a ViewModel like below :

public IEnumerable<Departure> Departures { get; set; }
public IEnumerable<Destination> Destinations { get; set; }
public IEnumerable<Airline> Airlines { get; set; }
public int count { get; set; }
public IEnumerable<Flight> Flights { get; set; }

flights has 3 other classes in it.

But I cant use this view model in my detail view :

<span class="glyphicon glyphicon-arrow-right"></span>
@Html.DisplayFor(Model => Model.flight.Departure.Name)

and this is my get method :

public ActionResult Add(int id)
{
    var flight = db.Flights.SingleOrDefault(f => f.Id == id);

    if (flight == null)
    {
        return HttpNotFound();
    }

    var viewModel = new BuyViewModel
    {
        Flights = db.Flights.ToList(),
    };

    return View(viewModel);
}

And I got error:

'BuyViewModel' does not contain a definition for 'flight' and no extension method 'flight' accepting a first argument of type 'BuyViewModel' could be found (are you missing a using directive or an assembly reference?)

Firstly your ViewModel has not a property named flight and it is Flights and secondly you should don't use Model as parameter in your lambda expression because it hides the Model property of the page.

Also please note that Flights is of type IEnumerable<Flight> and so you can't access to the Departure property. You should either change the type of the Flights to Flight and then:

@Html.DisplayFor(m => m.Flights.Departure.Name)

Or if you still want it to be IEnumerable then you can do something like this:

@Html.DisplayFor(m => m.Flights.Select(c => c.Departure).FirstOrDefault().Name)

Or iterate over Flights :

@foreach (var flight in Model.Flights) 
{
     @Html.DisplayFor(m => flight.Departure.Name) 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM