简体   繁体   English

如何将模型从数据库转移到编辑页面?

[英]How to transfer model to editpage from Data Base?

My input model consists of NewForm in which many fields 我的输入模型由NewForm组成,其中许多字段

public class NewForm
    {
         [Key]
        public int Id { get; set; }
        public string HeadForm { get; set; }

        public List<Field> Fields { get; set; }   
    }

    public class Field
    {
        public int Id { get; set; }
        public bool Check { get; set; }
        public string HeadField { get; set; }
    }

I want to take values from the base and edit them, but Model.Fields.Count throw exception. 我想从基础获取值并对其进行编辑,但是Model.Fields.Count抛出异常。 Although the string "HeadForm" is displayed. 尽管显示字符串“ HeadForm”。 Lists are not displayed. 列表不显示。 EditPage: EditPage:

@model EditFormApplication.Models.NewForm

@using (Html.BeginForm("Edit", "Home", FormMethod.Post))
{
    @Html.TextBoxFor(model => model.HeadForm)
    <h5>Fields:</h5><br>
        @for ( var i = 0; i< Model.Fields.Count; i++) {
          @Html.TextBoxFor(model => model.Fields[i].HeadField)                     
          @Html.CheckBoxFor(model => model.Fields[i].Check)
        }
        <input type="button" value="Add Field" onclick="addField(this);">
        <input type="submit"value="Save">
}

For example, I am typing data by ID = 3. Controller: 例如,我按ID = 3键入数据。

 public ActionResult CreateForm(NewForm model)
    {
        using (NewFormContext db = new NewFormContext())
        {
           db.NewForms.Add(model);
           db.SaveChanges();
           return RedirectToAction("Edit");
         }
     }

  public ActionResult Edit()
    {
        using (NewFormContext db = new NewFormContext()) { 
            var model = db.NewForms.Find(3);

        return this.View(model);
    }
    }

used Code First and one to many 使用过的代码优先和一对多

Sounds like Model.Fields property still contain null when db.NewForms.Find() is executed to assign the model you want to return into view, indicating that EF doesn't create dependent collection yet. 当执行db.NewForms.Find()分配要返回到视图中的模型时,听起来像Model.Fields属性仍然包含null,这表明EF尚未创建依赖集合。 As far as I know you should add collection instance definition inside parameterless constructor of entity class: 据我所知,您应该在实体类的无参数构造函数中添加集合实例定义:

public class NewForm
{
    public NewForm()
    {
        // instantiate list here
        Fields = new List<Field>();
    }

    [Key]
    public int Id { get; set; }
    public string HeadForm { get; set; }

    public List<Field> Fields { get; set; }   
}

Or if you're using lazy loading, mark the property as virtual to let EF instantiate the collection while necessary: 或者,如果您使用的是延迟加载,则将该属性标记为virtual以便在必要时让EF实例化集合:

public virtual List<Field> Fields { get; set; } 

Related issue: 相关问题:

EF codefirst : Should I initialize navigation properties? EF codefirst:我应该初始化导航属性吗?

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

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