【问题标题】:MVC Rendering a partial view in an EditorForMVC 在 EditorFor 中渲染局部视图
【发布时间】:2015-02-27 17:23:46
【问题描述】:

进一步了解here 建议的解决方案,我尝试过但没有成功 - 我想知道 razor 如何计算出呈现强类型化的局部视图?我按照建议做了,但感觉好像没有正确绑定并且缺少某些东西。

我的“子”模型:

public class Cohort
{
    public bool ukft { get; set; }
    public bool ukpt { get; set; }
    ...etc
}

我的强类型部分视图:

@model Models.Cohort

@Html.RadioButtonFor(model => Model.ukft, true) <span style="margin-right:8px;">Yes</span>
@Html.RadioButtonFor(model => Model.ukft, false) <span>No</span> <br />

我的主模型(其中包含 Cohort 对象列表):

public class OptOut
{
    public int optOutID { get; set; }
    public bool hasOptedOut { get; set; }        
    public List<Cohort> list { get; set; }

    public OptOut()
    {
        List<Cohort> list = new List<Cohort>();
        list.Add(new Cohort());
        list.Add(new Cohort());
        list.Add(new Cohort());
        list.Add(new Cohort());
        this.list = list;
    }
}

然后是我的html:

@model Models.OptOut
@using (Html.BeginForm("OptedOut", "Home"))
{   
    //this should supposedly figure out to render a partial view for each element in the list
    @Html.EditorFor(model => model.list)

    <div class="form-group" style="margin-top:25px;">
        <input id="confirm" type="submit" value="Confirm" class="btn btn-success btn-lg"/>
    </div>
}

【问题讨论】:

    标签: c# asp.net-mvc razor view model


    【解决方案1】:

    您似乎只是缺少EditorFor 和您的局部视图之间的联系。虽然EditorFor 确实使用了部分视图,但更恰当地说,它使用了所谓的“编辑器模板”。这些只是位置和文件名遵循特定约定的部分视图。

    也就是说,你的局部视图应该进入Views\Shared\EditorTemplates。 (创建目录。默认情况下不存在。)然后,它应该以它应该使用的类型命名。这里是Cohort,所以最终的路径和名称应该是:

    Views\Shared\EditorTemplates\Cohort.cshtml
    

    然后,EditorFor 将看到您有一个 Cohorts 列表,并使用 Cohort.cshtml 编辑器模板来呈现列表中的每个项目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-23
      • 2015-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多