views:

117

answers:

1

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);
}

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?

+1  A: 

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 ...

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.

JC Grubbs