让我们说我有以下课程(如果我的课程是正确的,你也可以考虑是否正确):

public class EFDbContext : DbContext
{
    public DbSet<Project> Projects { get; set; }
    public DbSet<Address> Addresses { get; set; } // *
    public DbSet<Country> Countries { get; set; } // *
    // Custom model builder bindings for * coz of the plural issue with EF
}

public class Project
{
    public int ProjectID { get; set; }
    public string Name { get ; set; }

    public int AddressID { get; set; } // Database relation column
    public Address Address { get ; set; }
}

public class Address
{
    public int AddressID { get; set; }
    public string Address1 { get ; set; }    
    public string Address2 { get ; set; }

    public int CountryID { get; set; } // Database relation column
    public Country Country { get ; set; }
}

public class Country
{    
    public int CountryID { get; set; }
    public string Name { get; set; }
}
.

我怎么会如何为此做剃刀...

我的“Create Project”页面需要一个看起来像这样的表单......但这不正确右?

@model Project

    <div class="form-group">
        @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Address, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Address)
        </div>
    </div>
. 所以我最终创建了一个生成的世代odetagcode,然后构建地址表单:

@model Address

    <div class="form-group">
        @Html.LabelFor(model => model.Address1, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Address1)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Address2, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Address2)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Country, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Country)
        </div>
    </div>
.

最后的国家......一个需要一个typeahead(所以一些自定义类添加到你不能这样做的Shared/EditorTemplates/Address.cshtml,所以我做了editorfor) - textbox

@model Country

    <div class="form-group">
        @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBox("", Model.Name.ToString(), new { @class = "countries typeahead" })
        </div>
    </div>
.

这看起来是否正确?我发现它非常压倒和令人困惑(顺便说一下,我已经尝试过这个,它不起作用......但如果我知道这是正确的方式,那么我就可以推动那个方向)!

有帮助吗?

解决方案

你在正确的轨道上。只要注意您在项目结构中将editements放置的位置以及您将如何引用它们。MVC公约并不总是按照您希望的方式工作。当模型包装在列表中时,使用编辑器模板进行单个模型。

一个建议我将使用完全单独的“查看模型”,以便将模型传递给剃须刀视图。您可以使用像automapper这样的东西之间的视图模型和实体框架模型(AKA数据模型)映射。为什么?你会发现随着时间的推移,他们需要不同的事情。模型属性的MVC属性。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top