本人有效以下視圖模型:ICollection的顯示爲空,ModelState中不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);
}
當我嘗試創建一張新卡片,viewModel的Sides屬性爲null,所以ModelState爲空。我無法弄清楚爲什麼最初的Side沒有通過模型傳遞。
我的視圖看起來是這樣的:
<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>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
您的觀點是什麼樣子? – 2013-02-10 19:08:47
我會在這裏添加它 – RobVious 2013-02-10 19:09:31