0

假设我有这个视图模型:

public class CreateGameViewModel
{
    [Required]
    public string SideA { get; set; }

    [Required]
    public string SideB { get; set; }

    [HiddenInput(DisplayValue = false)]
    public IEnumerable<int> ConfigurableCategoryIDs { get; set; }
}

而这些行动:

    [HttpGet]
    public ActionResult Create()
    {
        var viewModel = new CreateGameViewModel { ConfigurableCategoryIDs = new List { 1, 1, 1 } };
        return View(viewModel);
    }

    [HttpPost]
    public ActionResult Create(CreateGameViewModel viewModel)
    {
    ...
    }

在视图中,我尝试编辑 ConfigurableCategoryIDs 值:

    @for (int i = 0; i < Model.ConfigurableCategoryIDs.Count(); i++)
    {
        var item = Model.ConfigurableCategoryIDs.ElementAt(@i);
        @Html.EditorFor(m => item)
    }

CreateGameViewModel.ConfigurableCategoryIDs作为 null 返回到 Create(CreateGameViewModel viewModel),而 SideA 和 SideB 有值。

将不胜感激解释和解决方案!谢谢

4

1 回答 1

0

请尝试下一个:

模型:

public class CreateGameViewModel
{
    [Required]
    public string SideA { get; set; }

    [Required]
    public string SideB { get; set; }

    [HiddenInput(DisplayValue = false)]
    public List<int> ConfigurableCategoryIDs { get; set; }
}

控制器:

    [HttpGet]
    public ActionResult Create()
    {
        var viewModel = new CreateGameViewModel { ConfigurableCategoryIDs = new List<int> { 1, 1, 1 } };
        return View(viewModel);
    }

    [HttpPost]
    public ActionResult Create(CreateGameViewModel viewModel)
    {
        return View();
    }

看法:

@model MvcApplication1.Models.CreateGameViewModel

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>CreateGameViewModel</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.SideA)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.SideA)
        @Html.ValidationMessageFor(model => model.SideA)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.SideB)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.SideB)
        @Html.ValidationMessageFor(model => model.SideB)
    </div>

    @for (int i = 0; i < Model.ConfigurableCategoryIDs.Count(); i++)
    {
        @Html.EditorFor(m => Model.ConfigurableCategoryIDs[i])
    }

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
}
于 2012-09-02T19:46:24.953 回答