vamp123
vamp123

Reputation: 57

How to transfer model to editpage from Data Base?

My input model consists of NewForm in which many fields

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. Although the string "HeadForm" is displayed. Lists are not displayed. 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:

 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

Upvotes: 0

Views: 19

Answers (1)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

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

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

Related issue:

EF codefirst : Should I initialize navigation properties?

Upvotes: 1

Related Questions