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;
model.AllLemons = lemons; return View(model); }`
In View:
@using LemonTrader.Models.AllLemon
s
foreach(var item in Model.LemonList)
{
@item.Some
}
If in result you will have null, it will be a blank page
Have fun!
精彩评论