Displaying null IEnumerable with EditorTemplate

130 views Asked by At

I have a complex object which has a IEnumerable property and that I want to display in my view.

For that purpose I've created an EditorTemplate for that list.

So, in my view I have the following code:

<div id="tabMed" class="tab-pane">
    <fieldset>   
        <div>
            @Html.EditorFor(m => m.MyList)
        </div>
    </fieldset>
</div>

m.List is an IEnumerable type and the Editor template has inside some fields for displaying the object.

This works fine when the list has 1 or more objects; it will display and repeat the template for every object in that list.

Now the problem:

Let's supose that I want to edit the object that contains that list and the IEnumerable property is null. The Editor template won't appear at all, leaving no possibility to create the first object in that list.

Is there any approach to show an empty template if the list is null without having to something like this?:

<div id="tabMed" class="tab-pane">
    <fieldset>   
        <div>
            @if (Model.MyList.Count() > 0)
            {
                @Html.EditorFor(m => m.MyList)
            }
            else
            {
                // empty object form template here...
            }
        </div>
    </fieldset>
</div>

Edit: The EditorTemplate look like this:

@model Jazz.Models.MyList.MyObject

<div class="control-group">
    @Html.LabelFor(model => Model.Name, new { @class="control-label"})
    <div class="controls">
        @Html.TextBoxFor(m => m.Name, new { @class="collection-item", autocomplete = "off", maxlength = 64 })
    </div>
</div>

The MyList is the list that I want to display

The MyObject class is declared inside MyList

So, the model would be like this:

public class MyList
{
    public MyList()
    {
        this.list = new List<MyObject>();
    }

    public int id{ get; set; }

    public List<MyObject> list{ get; set; }

    public class MyObject
    {
        public MyObject(){}

        public string Name{ get; set; }

    }
}

I've put the example in a generic way so it's simplier to show the problem.

0

There are 0 answers