简体   繁体   English

如何将ICollection属性绑定到MVC4视图?

[英]How to bind ICollection property to MVC4 View?

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. 由于ICollection没有索引器,因此在将ICollection Options绑定到视图时ICollection Options问题。

@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 ? 这是将ICollection绑定到视图的正确且通用的方法吗?

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: 只是给您一个不同的预期,一个干净的解决方案是使用EditorTemplates(将摆脱所有循环),所以它是这样的:

@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 然后继续并在-〜 ~/Views/Shared/EditorTemplates/Question.cshtml下创建相应的EditorTemplate

@model LakshyaMvc.Models.Question

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

Then of couse the corresponding EditorTemplate for the options: 然后将相应的EditorTemplate用作选项:

~/Views/Shared/EditorTemplates/Option.cshtml

@model LakshyaMvc.Models.Option
@Html.RadioButtonFor(m => m.Title, Model.Title, new { @name = "uniqueRadio" })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM