I’ve had some success passing query results to my view.
Unfortunately the ASP/Razor code balks in the foreach when the resulting model list has 0 entries.
@foreach (var action in (List<LemonTrader.Models.Lemon>)ViewData["lemons"]) {
<tr>
<td>
@Html.Encode( action.acidity)
If there are no entries it says something about a null exception.
What is the best way to handle the case where the list is empty?
I guess I could put a code block in and have it do an if/then branch. This seems to deviate a bit from the elegant razor one-liner of @foreach.
I guess I could put blank stuff in the controller and then just display something blank.
Those don’t seem like very elegant approaches.
Any better ideas?
Try do next:
Create additional model (viewmodel) in Models folder (for example LemonsView.cs) and put there:
public class LemonList{
public IQueryable<Lemon> AllLemons { get; set; }
}
Create a controller (LemonController.cs)
public ActionResult Lemons{var model = new LemonList();var lemons = db.Lemon;In View:
@using LemonTrader.Models.AllLemonsforeach(var item in Model.LemonList){@item.Some}If in result you will have null, it will be a blank page
Have fun!