As simple as I can explain this... I have a User object, which has Privilege(s). Privileges are of course another table using FK's to link them together.
In my User Edit page, I have an EditorFor for the privileges (which is working fine), which includes a remove button (also working fine)...
What I'm not sure about is how to add a new item to the table, and have that item be submitted with the rest of the privileges. I could just be burnt out from a long day of coding, so if I'm being dumb, just say so...
Anyways, some code:
Edit.cshtml
<div class="form-group">
@Html.LabelFor(model => model.Privileges, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<table class="table-striped">
<col style="width:40%; padding-right: 10px">
<col style="width:10%">
<col style="width:10%">
<col style="width:10%">
<thead>
<tr>
<td>Facility</td>
@foreach (var t in ViewBag.InitTypes)
{
<td>@t.Abbreviation</td>
}
</tr>
</thead>
@Html.EditorFor(m => m.Privileges)
</table>
</div>
</div>
function removeItem(item) {
$('#priv_' + item).remove();
}
Privilege.cshtml (Template)
@model ENT_ComplianceInitiatives2_Web.Models.Privilege
@Html.HiddenFor(model => model.UserID)
@Html.HiddenFor(model => model.ID)
<tr id="priv_@Model.ID">
<td>@Html.DropDownList("FacilityID")</td>
<td>@Html.EditorFor(model => model.C)</td>
<td>@Html.EditorFor(model => model.P)</td>
<td>@Html.EditorFor(model => model.S)</td>
<td><i class="fa fa-trash" onclick="removeItem(@Model.ID)"></i></td>
</tr>
And of course a screenshot showing how it comes out.
EDIT: Here's some code from my controller that I currently have in place.
for (int i = user.Privileges.Count - 1; i >=0; i--)
{
var p = user.Privileges.ElementAt(i);
var priv = db.Privileges.Find(p.ID);
if (priv == null)
{
//ok, we need to add it
priv = db.Privileges.Create();
priv.C = p.C;
priv.P = p.P;
priv.S = p.S;
priv.UserID = user.ID;
db.Privileges.Add(priv);
}
else if (p.FacilityID == 0)
{
//remove it - when removing the row from the table, the facilityID gets set to 0
db.Privileges.Remove(priv);
}
else
{
//update it
priv.C = p.C;
priv.P = p.P;
priv.S = p.S;
db.Entry(priv).State = EntityState.Modified;
}
}