在MVC4剃刀视图InvalidOperationException

问题描述:

我想构建一个flashcard应用程序来学习MVC4。套装包含卡片,卡片包含边框(以方便一张或多面卡片)。在MVC4剃刀视图InvalidOperationException

我有以下视图模型为创建卡:

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; } 

    } 

并为创建定义以下操作:

[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); 


     } 

在视图中,我试图通过显示一边启动我在Controller中创建并允许用户编辑它。我得到“InvalidOperationException:模板只能用于字段访问,属性访问,单维数组索引或单参数自定义索引器表达式。”当我尝试在视图中使用以下标记运行时:

<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> 
} 

如何在创建卡时让用户编辑现有侧?

而不是使用ElementAt()的,只需要使用普通[]指数操作:

@Html.EditorFor(model => model.Sides[side.SideId])

+0

我尝试这样做,我得到的,说:“不能将编入索引类型的ICollection的表达错误 – RobVious 2013-02-10 20:59:46

+0

您能改用IList? – 2013-02-10 21:13:46