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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Asp.Net C# MVC Dynamic Forms (Changing Dom structure and getting data on the server)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.