0

I have a many-to-many relationship with 3 tables. Employee, History and Title. The History-table contains a timespan and a relationship to both the employee and title.

In the end I want to be able to edit both the timespan and title for each employee from a common view. In employeeController.cs I've got this code for when I submit the form.

[HttpPost, ActionName("Edit")]
[ValidateAntiForgeryToken]
public ActionResult Edit(employee empl) // Note: I have no bindings here, either. Should I?
    if (ModelState.IsValid)
    {
        db.Entry(empl).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(empl);
}

But the object empl doesn't have anything in it's Histories-collection. It simply says Count = 0. How can I include both my History (and later the Title-table) so that I can update that, too?

Some of my employee.cs:

public partial class employee
{
    public employee()
    {
        this.Histories = new HashSet<Histories>();
    }
    public virtual ICollection<Histories> Histories { get; set; }
}

For reference, this shows up correctly in Edit.cshtml for employee:

<table class="table">
<tr>
    <th>Start date</th>
    <th>End date</th>
    <th>Title</th>
</tr>
@foreach (var item in Model.Histories.OrderByDescending(x => x.fromdate))
{
    <tr>
        <td>
            @Html.EditorFor(modelItem => item.fromdate)
        </td>
        <td>
            @Html.EditorFor(modelItem => item.todate)
        </td>
        <td>
            @Html.EditorFor(modelItem => item.Title.Title)
        </td>
    </tr>
}
</table>

If more info is needed, feel free to ask, and sorry for any typos. I had to translate all class names to english so you'll understand better.

PWL
  • 456
  • 4
  • 27

1 Answers1

0

use seomthing like this:

            for (int i = 0; i <  Model.Histories.OrderByDescending(x => x.fromdate).Count(); i++)
            {
                <tr>
                    <td>
                        @Html.HiddenFor(modelItem => Model.Histories[i].fromdate)                            
                        @Html.EditorFor(modelItem => Model.Histories[i].fromdate)                            
                    </td>
                    <td>
                        @Html.HiddenFor(modelItem => Model.Histories[i].todate)                            
                        @Html.EditorFor(modelItem => Model.Histories[i].todate)   
                    </td>
                    <td style="text-align: center">
                        @Html.HiddenFor(modelItem => Model.Histories[i].Title.Title)                            
                        @Html.EditorFor(modelItem => Model.Histories[i].Title.Title)                             
                    </td>
                </tr>
            }
alaa_sayegh
  • 2,141
  • 4
  • 21
  • 37