开发者

model size check

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:

  1. Create additional model (viewmodel) in Models folder (for example LemonsView.cs) and put there:

    public class LemonList { public IQueryable<Lemon> AllLemons { get; set; } }

  2. Create a controller (LemonController.cs)

    public ActionResult Lemons
    {
    var model = new LemonList();
    var lemons = db.Lemon;

        model.AllLemons = lemons;
        return View(model);
    }`
    
  3. In View:

    @using LemonTrader.Models.AllLemons
    foreach(var item in Model.LemonList){
    @item.Some
    }

If in result you will have null, it will be a blank page

Have fun!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜