在ViewModel中设置默认值而不在View中列出属性 - 可能吗? MVC4

时间:2013-02-11 18:49:38

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

我有以下控制器:

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

0 个答案:

没有答案