Jose3d
Jose3d

Reputation: 9277

MVC dynamic form how to add validation

I want to build a dynamic form from the scratch, and i already created the following elements:

A xml file with all fields that i want to show:

<?xml version="1.0" encoding="utf-8" ?>
<Fields>
    <FieldList>
        <Field>
            <Type>checkbox</Type>
            <Name>gender</Name>
            <DefaultValue>false</DefaultValue>
            <CssClass>myclass</CssClass>
        </Field>
        <Field>
            <Type>textbox</Type>
            <Name>name</Name>
            <DefaultValue>fill name</DefaultValue>
            <CssClass>formtextbox</CssClass>
        </Field>
    </FieldList>
</Fields>

A view typed to a class that i used to deserialize the xml:

@model Fields
@{
    if(Model!=null)
    {
        using (Html.BeginForm())
        {
            foreach (Field field in Model.FieldList)
            {
                switch(field.Type)
                {
                    case "textbox":
                        @Html.TextBox(field.Name, field.DefaultValue);
                    break;

                    case "checkbox":
                        @Html.CheckBox(field.Name,Convert.ToBoolean(field.DefaultValue));
                    break;
                }
            }    
        }
    }
}

By the moment the app is working properly but i have the following doubts:

1) I think is not an elegant solution since i have to put too many code in the view right?

2) I would like to add now some server validation. I normally work with data annotations, but here is not possible i guess since i dont know how is the thing that im submitting. Is there any way to create on the fly an class instance and add data anotations on the fly?

3) I created another action and controller that will handle the post. Since i dont know what im submitting my action doesnt receive as parameter nothing. I guess i have to use Request.Form from my action right?

Upvotes: 1

Views: 1183

Answers (2)

JTMon
JTMon

Reputation: 3199

My first thought was to implement a custom HtmlHelper method that will take the XML and generate the view for you. Like that you would only have one line of code in your view.
As for validation, you can extend DataAnnotationsModelValidatorProvider and override GetValidators() to inject default mvc validators and/or your own validators based on whatever parameters or policies you see fit. These would be propagated to the client side as well.

Upvotes: 1

denis
denis

Reputation: 1

I suggest to add more than one type :

abstract class Field {
     public string Name {get;set; }
}

class BooleanField : Field{
     public bool Value { get;set; }
}

class TextField : Field{
      public string ValidationRegEx { get; set }
      public string Value { get;set; }
}

and etc.

Also add editor template for each type

To add validation for TextField you can create custom validation attribute which checks that value matched to validation reg ex

Upvotes: 0

Related Questions