简体   繁体   English

MVC在EditorFor中渲染局部视图

[英]MVC Rendering a partial view in an EditorFor

Further to the solution that was suggested here , which I tried but didn't work - I wanted to know how razor figures out to render a strongly typed partial view? 除了这里提出的解决方案,我试过但没有用 - 我想知道razor如何计算出一个强类型的局部视图? I did what was suggested but it feels like it's not tied up properly and something is missing. 我按照建议进行了操作,但感觉它没有正确绑定而且缺少某些东西。

My "sub" model: 我的“子”模型:

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

My strongly typed partial 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 />

My main model (which contains a list of Cohort objects): 我的主模型(包含群组对象列表):

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

and then my html: 然后我的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>
}

It seems you're just missing the connection between EditorFor and your partial view. 看起来你只是错过了EditorFor和你的局部视图之间的EditorFor While EditorFor does use partial views, more appropriately, it uses what's called "editor templates". 虽然EditorFor 确实使用了部分视图,但更恰当的是,它使用了所谓的“编辑器模板”。 These are just partial views whose location and filename follow a particular convention. 这些只是部分视图,其位置和文件名遵循特定约定。

Namely, your partial view should go in Views\\Shared\\EditorTemplates . 也就是说,您的局部视图应该位于Views\\Shared\\EditorTemplates (Create the directory. It doesn't exist by default.) Then, it should be named after the type it should be utilized with. (创建目录。默认情况下它不存在。)然后,它应该以它应该使用的类型命名。 Here, that's Cohort , so the final path and name should be: 在这里,这是Cohort ,所以最终的路径和名称应该是:

Views\Shared\EditorTemplates\Cohort.cshtml

Then, EditorFor will see that you have a list of Cohort s and use the Cohort.cshtml editor template to render each item in the list. 然后, EditorFor将看到您有一个Cohort列表,并使用Cohort.cshtml编辑器模板呈现列表中的每个项目。

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

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