3

I have a registration page, which asks for some data from the user, e.g. email address. Administrators should be able to customize the form. For example, he may be interested in the birthplace of the user, in which case an additional textbox should appear in the registration form.

Because the fields in the form are so dynamic, I can not add these as properties to the viewmodel. How can I add input controls and validators to the view at runtime?

3

2 Answers 2

1

You can create a model class for your dynamic form using a collection. For example:

public class MyParam {
  public string Name {get; set;}
  public string Value{get; set;}
}

public class MyDynamicForm {
  public List<MyParam> parameters {get; set;}
}

Than you can create a view that build the form using a loop on the parameters. To validate the input parameters, you need to develope a validation method that receive in input the FormCollection and validate every parameter by Name.

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

Comments

0

I solved this in the following less-than-optimal way:

In my view, I loop through my custom attributes and call an extension method on the HtmlHelper to render the Html:

foreach (var attribute in group.Attributes)
{ 
<tr>
    <td>
        @attribute.Name
    </td>
    <td>
        @Html.ValidationMessage(attribute.Id)
        @Html.AttributeEditor(attribute)
    </td>
</tr>
}

In the AttributeEditor() method, I set the unobtrusive Javascript validation attributes to enable client-side validation:

    if (IsRequired)
    {
        attributes["data-val-required"] = MvcCompaniesResources.UserProfileValidatorMessages.RequiredField;
        attributes["data-val"] = "true";
    }

This gives client side validation, and works well with @Html.ValidationMessage(). However, I would still need to implement server-side validation separately.

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.