我有一個ASP.NET MVC視圖以下形式:在ASP.NET驗證動態創建的字段MVC
<%= Html.ValidationSummary() %>
<% var fields = ViewData.Model; %>
<% using (Html.BeginForm("Dynamic", "Candidate")) { %>
<% foreach (var field in fields) { %>
<label for="<%= field.FieldName %>"><%= field.FieldName %></label>
<%= Html.TextBox(field.FieldName, field.Value, new { @class = "short" }) %>
<% } %>
<a class="button green" onclick="$('form').submit(); return false;">Submit</a>
<% } %>
我有加載這種形式以及接受後的單個控制器的動作,它看起來是這樣的:
public ActionResult Dynamic() {
var fields = DataProvider.Candidates.GetAllDynamicFields();
if (Request.HttpMethod == "POST") {
fields.ForEach(f => f.Value = Request[f.FieldName]);
var validation = DataProvider.Candidates.SaveDynamicFields(fields);
if (validation.IsValid)
return RedirectToAction("Index");
ViewData.ModelState.AddErrorsFromValidationResult(validation);
}
return View(fields);
}
我的問題是,如果任何驗證失敗(即驗證對象包含錯誤),那麼我在視圖渲染得到一個錯誤,因爲ViewData.ModelState不含任何按鍵。我在哪裏錯了?任何線索?