验证在ASP.NET MVC中动态创建领域 [英] Validating dynamically created fields in ASP.NET MVC
问题描述
我有一个ASP.NET MVC视图的格式如下:
I have the following form in an ASP.NET MVC view:
<%= 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>
<% } %>
我有这种加载形式以及接受后一个控制器的动作,它看起来像这样:
I have a single controller action that loads this form as well as accepts the post, it looks like this:
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不包含任何键。我在哪里去错在这里?任何线索?
My problem is that if any of the validators fail (i.e. the validation object contains errors) then I get an error on view rendering because ViewData.ModelState doesn't contain any keys. Where am I going wrong here? Any clues?
推荐答案
想通了。 ViewData.ModelState是在响应对象的PARAMS填充。因此,与动态创建的形式,你不知道到底发生了什么在后通过。所以,我只是重新对飞我的ModelState:
Figured it out. ViewData.ModelState is populated by the params in the response object. So with a dynamically created form you don't know exactly what was passed in the post. So I just recreate my ModelState on the fly:
fields.ForEach(f => ViewData.ModelState.Add(f.FieldName ...
然后,我们都好......当被验证的观点可以发现在ModelState中,并没有异常的所有键运行......就像一个魅力。
And then we're all good...when the validation is run on the view it can find all the keys in the ModelState and no exceptions...works like a charm.
这篇关于验证在ASP.NET MVC中动态创建领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!