0

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

我有以下用于卡片创建的视图模型:

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 中创建的 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>
}

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

4

1 回答 1

1

Instead of using ElementAt(), just use the normal [] index operator:

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

于 2013-02-10T20:09:37.320 回答