我有以下控制器:
[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>
}