I have a form page that should update multiple rows in a database table. I have used ViewModel to generate the Form page UI.
I want each row in the UI table to be send as a row to the database table.
The OptionValueID is set in the controller. But the value for the TcSetID comes from the ID of the Property in the UI.
Controller
public ActionResult Create()
{
var viewmodel = new AddSetValue
{
SetValue = new SetValue{
OptionValueID = 6
}
};
viewmodel.SetValue.OptionValueID = 6;
var ov = db.OptionValue.Include(x => x.Option).FirstOrDefault(x => x.OptionValueID == 6);
var opid = ov.OptionID;
var op = db.Option.Include(x => x.TechnicalCharacteristic).FirstOrDefault(x => x.OptionID == opid);
var tcid = op.TechnicalCharacteristicID;
var tcset = db.TechnicalCharacteristic.Include(x => x.TcSets).FirstOrDefault(x => x.TechnicalCharacteristicID == tcid);
viewmodel.TcSet = tcset.TcSets;
return View(viewmodel);
}
ViewModel AddSetValue
public class AddSetValue
{
public virtual SetValue SetValue { get; set; }
public virtual ICollection<TcSet> TcSet { get; set; }
}
View (Excerpt where ViewModel is being used)
@foreach(var item in Model)
{
int count = 0;
foreach (var set in item.TcSet)
{
<tr>
<td>
@Html.HiddenFor(model=>model[count].SetValue.TcSetID)
@set.SetName
</td>
<td>
<div class=" col-md-10">
@Html.EditorFor(model => model[count].SetValue.Value, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model[count].SetValue.Value, "", new { @class = "text-danger" })
</div>
</td>
<td>
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model[count].SetValue.Status, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model[count].SetValue.Status, "", new { @class = "text-danger" })
</div>
</div>
</td>
</tr>
count++;
}
}
I need to submit all the values to the Create method that saves the value to the table. The data in the database table in the image was added manually.
As i have read in other answers I should index each row in my View and has to commit it each row in a forloop in my Post Create method. But I am unable to assign a list at the moment.
Are there any other ways to commit multiple rows to the database?
[1]: http://i.stack.imgur.com/wKjsn.png
[2]: http://i.stack.imgur.com/srtab.png