使用MVC4的Razor View中的InvalidOperationException

时间:2013-02-10 19:35:34

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我正在尝试构建一个flashcard应用程序来学习MVC4。套装包含卡片,卡片包含侧面(方便一张或多张卡片)。

我有以下用于创建卡片的viewModel:

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

    }

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


        }

在视图中,我试图首先显示我在Controller中创建的Side,并允许用户编辑它。我得到“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>
}

如何在创建卡片时让用户编辑现有的边?

0 个答案:

没有答案