简体   繁体   中英

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? 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:

@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. While EditorFor does use partial views, more appropriately, it uses what's called "editor templates". These are just partial views whose location and filename follow a particular convention.

Namely, your partial view should go in 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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