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?

tereško
  • 58,060
  • 25
  • 98
  • 150
Sjoerd
  • 74,049
  • 16
  • 131
  • 175
  • [ASP.Net MVC Editor template for dynamic view data / forms](http://stackoverflow.com/questions/7403799/asp-net-mvc-editor-template-for-dynamic-view-data-forms) – Sjoerd Oct 03 '11 at 12:52
  • [ASP.NET MVC Custom ModelMetadataProvider and ModelValidatorProvider](http://stackoverflow.com/questions/4602339/asp-net-mvc-custom-modelmetadataprovider-and-modelvalidatorprovider) – Sjoerd Oct 04 '11 at 09:40
  • [Dynamic ASP.NET MVC 3 models using Mono’s Compiler as a Service](http://weblogs.asp.net/jgalloway/archive/2011/05/26/dynamic-asp-net-mvc-3-models-using-mono-s-compiler-as-a-service.aspx) – Sjoerd Oct 06 '11 at 08:54

2 Answers2

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.

Massimo Zerbini
  • 3,125
  • 22
  • 22
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.

Sjoerd
  • 74,049
  • 16
  • 131
  • 175