0

I have defined a model as below-

public class Question
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int UserSelection { get; set; }

    public Question()
    {
        this.Options = new List<Option>();
    }
    public virtual ICollection<Option> Options { get; set; }        
}

Since ICollection does not have indexer, I am facing problem in binding ICollection Options to the view.

@model List<LakshyaMvc.Models.Question>

<ol class="Quest">
            @for (int i = 0; i < Model.Count; i++)
            {
                var quest = Model[i];
                <li>
                    @Html.LabelFor(x => quest.Title, quest.Title)
                    <ol class="Opt"> 
                        @for (int j = 0; j < quest.Options.Count; j++)
                        {
            @*Indexer not availabl here *@  
                            <li class="Opt">
                                @Html.RadioButtonFor(o => quest.Options[j].Title, quest.Options[j].Title, new { @name = "uniqueRadio" })  
                            </li>
                        }
                    </ol>
                </li>

            }
        </ol>

The temporary solution I am going to adapt is create partial view for displaying Options. defining model as below -

@model List<LakshyaMvc.Models.Option>

Is this the correct & general approach to bind ICollection to the view ?

Aron
  • 15,464
  • 3
  • 31
  • 64
Abhijeet
  • 13,562
  • 26
  • 94
  • 175
  • 1
    Any reason you can't change it to something with an indexer? Say... a `List`? – Simon Whitehead Aug 05 '13 at 04:39
  • @SimonWhitehead, ICollection is more suitable when collection has to be altered, in case of CRUD operations. List and IEnumarables are primarily suited for iterating the list items. – Abhijeet Aug 06 '13 at 18:00

1 Answers1

0

Just to give you a different prospective, a clean solution would be to use EditorTemplates (will get rid of all the loops), so it goes like this:

@model List<LakshyaMvc.Models.Question>

<ol class="Quest">
    @Html.EditorForModel()
</ol>

Then go on and create the corresponding EditorTemplate under - ~/Views/Shared/EditorTemplates/Question.cshtml

@model LakshyaMvc.Models.Question

<li class="Opt">
    @Html.EditorFor(m => m.Options)
</li>

Then of couse the corresponding EditorTemplate for the options:

~/Views/Shared/EditorTemplates/Option.cshtml

@model LakshyaMvc.Models.Option
@Html.RadioButtonFor(m => m.Title, Model.Title, new { @name = "uniqueRadio" })
Dimitar Dimitrov
  • 14,868
  • 8
  • 51
  • 79