Reputation: 93
How would I edit repeating fields in a form (multiple values for same model property)? I am using Visual Studio 2013 ASP.NET MVC 5 Entity Framework code first with the Razor syntax.
I have managed to get the create functionality working which adds the data to the database successfully but how would I go about bringing these values back into the edit view to edit and re-save back to the database? e.g.
How My View Looks
Enter Description | Enter Amount
Description1TextBox | Amount1TextBox
Description2TextBox | Amount2TextBox
Description3TextBox | Amount3TextBox....
@for (int i = 0; i < 5; i++)
{
<div class="row">
@Html.TextBoxFor(m => Model.Options[i].Description, new { @class = "form-control col-sm-6" })
@Html.TextBoxFor(m => Model.Options[i].Amount, new { @class = "form-control col-sm-6" })
</div>
}
My ViewModel
An Array
...
public string Description { get; set; }
public decimal? Amount { get; set; }
public Options[] Options { get; set; }
...
My Create Controller Post ActionResult
....
foreach (var optionsLoop in viewModel.Options)
{
if (optionsLoop.Description != null || optionsLoop.Amount != null)
{
var options = new Options()
{
Id = getId,
Description = optionsLoop.Description,
Amount = optionsLoop.Amount
};
db.Options.Add(options);
}
}
await db.SaveChangesAsync();
What do I need to change to bring the values back into the edit view to then edit? I can do a Linq query in the edit controller action to return a list to get the values I want in my edit view but how do I pass these values from the Linq query to the loop in my view?
...
//Values to bring back into my edit view
var getOptions = (from options in db.Options
where options.Id == currentUser.Id
select new { options}).Take(5).ToList();
...
Upvotes: 0
Views: 344
Reputation:
Change you model property to
public List<Option> Options { get; set; }
and in the controllers GET method, assign it using
model.Options = getOptions; // populate the options
return View(model);
and in the view
@for (int i = 0; i < Model.Options.Count; i++)
{
<div class="row">
@Html.TextBoxFor(m => m.Options[i].Description, new { @class = "form-control col-sm-6" })
@Html.TextBoxFor(m => m.Options[i].Amount, new { @class = "form-control col-sm-6" })
</div>
}
Upvotes: 1