【问题标题】:MVC EditorTemplate for list that is not part of the model不属于模型的列表的 MVC EditorTemplate
【发布时间】:2012-03-07 08:16:41
【问题描述】:

在我看来,我称列表为局部视图。在该部分视图中,我将该列表分成两个 IEnumerable,对于每个列表,我想为 ModelType 调用 EditorTemplate:

我的部分视图:

@model List<ModelType>

@using System.Collections;         

@{
    int countModelTypeLeft = (Model.Count % 2 != 0) ? Model.Count + 1 : Model.Count ;
    int countModelTypeRight = Model.Count;

    IEnumerable<ModelType> modelTypeListLeft = Model.Take(countModelTypeLeft);
    IEnumerable<ModelType> modelTypeListRight = Model.Range(countModelTypeLeft , countModelTypeRight );
}
    <div class="modeltype-left" style="float: left; width: 50%;">
        // How can I call EditorFor for modelTypeListLeft  now?
    </div>

    <div class="modeltype-right" style="float: right; width: 50%;">
        // How can I call EditorFor for modelTypeListRight  now?
    </div>

如您所见,我被卡住了,因为我无法调用 EditorFor,因为两个列表 modelTypeListLeft 和 countModelTypeRight 不是局部视图中给定模型的一部分。如何解决这个问题?

【问题讨论】:

    标签: model-view-controller mvc-editor-templates editortemplates


    【解决方案1】:

    如果您有 ModelType 的编辑器模板,那么这仍然可以工作并使用正确的编辑器模板

    <div class="modeltype-left" style="float: left; width: 50%;">        
        @foreach(var leftItem in modelTypeListLeft )
        {
            Html.EditorFor(m=>leftItem)
        }
    </div>
    
    <div class="modeltype-right" style="float: right; width: 50%;">        
        @foreach(var rightItem in modelTypeListRight)
        {
            Html.EditorFor(m=>rightItem)
        }
    </div>
    

    【讨论】:

    • 我想利用使用 IEnumberable 调用 @Html.EditorFor 的事实使 MVC 为给定模型选择正确的 EditorTemplate。但是您的回答给了我正确的提示:@Html.EditorFor(model =&gt; modelTypeListLeft ) 为列表中的每个项目调用 EditorTemplate!但无论如何我不知道MVC中的参数表达式总是意味着我必须给出给定模型的一部分但你只是证明了事实并非如此。如何了解更多关于表达的知识?
    • :),不确定我可以为您指出哪些资源...编写更多代码肯定会有所帮助;)
    • 如果答案有任何意义,请您将其标记为答案。(:P Greedy)
    猜你喜欢
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多