Pergunta

I have a razor view and supposed to return a list of customers:

@model IEnumerable<myapp.Models.customers>
@{
    ViewBag.Title = "customers";
}

@Model.First().Order.Name

Displaying the customer details works fine that is not the issue. I would like to display the name of the Order once at the top. The relation for Order to Customer is 1 to many so some Orders can have no Customers. That is when I get this error:

[InvalidOperationException: Sequence contains no elements]
   System.Linq.Enumerable.First(IEnumerable`1 source) +269

the question is how can I check this on the Razor view and display a user friendly message?

Nenhuma solução correta

Outras dicas

You can always evaluate the first order by checking if the first customer's order is null or not...

 @{
        if(Model.FirstOrDefault() != null && Model.FirstOrDefault().Order != null)
        {
            <span class="order-name">Model.First().Order.Name</span>
        }
        else
        {
            <span class="order-error">Error Message</span>
        }
    }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top