c# - MVC 在 EditorFor 中渲染局部 View

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

关于建议的解决方案 here ,我试过但没用——我想知道 Razor 是如何渲染强类型局部 View 的?我按照建议做了,但感觉它没有正确捆绑并且缺少某些东西。

我的“子”模型:

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

我的强类型局部 View :

@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 />

我的主要模型(包含队列对象列表):

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>
}

最佳答案

看来您只是缺少 EditorFor 和您的部分 View 之间的连接。虽然 EditorFor 确实 使用部分 View ,但更恰本地说,它使用所谓的“编辑器模板”。这些只是部分 View ,其位置和文件名遵循特定约定。

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

Views\Shared\EditorTemplates\Cohort.cshtml

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

关于c# - MVC 在 EditorFor 中渲染局部 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28770808/

相关文章:

javascript - 对于在 javascript 和 html 中无法正常工作

c# - @: and <text> in Razor 之间的区别

c# - 从 @html.DropDownList 返回 int 值

javascript - 我的模态弹出窗口中的 .submit(function ()) 不起作用,我的模态弹出窗口将发送正常的 http post 请求

c# - C# 中的可选参数 - 将用户定义的类默认为 null

c# - 是否为每个新实例实例化基类?

c# - 是否有一些实现日志记录功能的类,我可以使用?

c# - File.ReadAllText() 和使用 StreamReader 读取文件内容有什么区别?

javascript - 另一个ajax正在运行时进行Ajax轮询

javascript - 分别编辑每个div