1

我有以下控制器:

[HttpGet]
public ActionResult Create(int setId)
{
    // create new viewModel
    var model = new CreateCardViewModel() {SetId = setId};

    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
            {
                Set=set, 
                SetId = set.SetId, 
                Sides = viewModel.Sides, 
                DateCreated = viewModel.DateCreated, 
                IsReady = viewModel.IsReady, 
                Stage = viewModel.Stage
            };
        set.Cards.Add(card);

        _db.Save();

        return RedirectToAction("detail", "set", new {setId = viewModel.SetId});
    }
    return View(viewModel);
}

使用以下 ViewModel:

public class CreateCardViewModel
    {
        public CreateCardViewModel()
        {
            DateCreated = DateTime.Now;
            Sides = new List<Side> {new Side() {Stage = 0, IsFront = true, IsReady = false, Content = "Blank Side"}};
            Stage = 0;
            IsReady = true;
        }

    [HiddenInput(DisplayValue = false)]
    public int SetId { get; set; }

    [Required]
    public IList<Side> Sides { get; set; }

    [Required]
    public int Stage { get; set; }

    [Required]
    [DataType(DataType.Date)]
    [HiddenInput(DisplayValue = false)]
    public DateTime? DateCreated { get; set; }

    [Required]
    public bool IsReady { get; set; }

}

但是,当我从视图中发回时,我的数据ViewModel都不会返回到控制器,因为视图永远不会看到它。创建这些默认值而不必在 ? 中列出它们的最佳方法是View什么?在视图中列出参数似乎很不雅。也许我应该在Controller?

我的观点在这里:

@model Project.Models.CreateCardViewModel

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>CreateCardViewModel</legend>

        @for (var i = 0; i < Model.Sides.Count; i++)
        {
            <h3>Side @(i+1)</h3>
            @Html.EditorFor(x => x.Sides[i].Content)
        }

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
4

0 回答 0