I’m trying to build a flashcard application to learn MVC4. A Set contains Cards, and a Card contains Sides (to facilitate one or many-sided cards).
I have the following viewModel for Card Creation:
public class CreateCardViewModel
{
[HiddenInput(DisplayValue = false)]
public int SetId { get; set; }
[Required]
public ICollection<Side> Sides { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime DateCreated { get; set; }
[Required]
public bool IsReady { get; set; }
}
And the following actions defined for Create:
[HttpGet]
public ActionResult Create(int setId)
{
var model = new CreateCardViewModel();
// attach card to current set
model.SetId = setId;
// create a new Side
var side = new Side() {Content = "Blank Side"};
// Add this to the model's Collection
model.Sides = new Collection<Side> { side };
return View(model);
}
[HttpPost]
public ActionResult Create(CreateCardViewModel viewModel)
{
if (ModelState.IsValid)
{
var set = _db.Sets.Single(s => s.SetId == viewModel.SetId);
var card = new Card {Sides = viewModel.Sides};
set.Cards.Add(card);
_db.Save();
}
return View(viewModel);
}
In the view, I’m trying to start by displaying the Side that I created in the Controller, and allowing the user to edit it. I get “InvalidOperationException: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.” when I try to run with the following markup in the view:
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>CreateCardViewModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.SetId)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.SetId)
@Html.ValidationMessageFor(model => model.SetId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.DateCreated)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.DateCreated)
@Html.ValidationMessageFor(model => model.DateCreated)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.IsReady)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.IsReady)
@Html.ValidationMessageFor(model => model.IsReady)
</div>
// OFFENDING CODE
@foreach (var side in Model.Sides)
{
@Html.EditorFor(model => model.Sides.ElementAt(side.SideId))
}
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
How can I let the user edit the existing Side when creating a card?
Instead of using
ElementAt(), just use the normal[]index operator:@Html.EditorFor(model => model.Sides[side.SideId])