I have a very large model for user profiles. There are about 15 different new user categories (e.g., young traveler, experienced traveler, captain, helmsman, ...). Depending on the user category, some data fields of the model are not applicable and remain null in the database.
I'm trying to populate the model through one big sign-up form. JavaScript determines the user category based on the user's previous answers and shows/hides applicable/non-applicable input fields in the form.
The following problem arose:
Depending on the user category, I need to show some input fields in a slightly different order in the form. I have solved this by creating multiple input fields for the same data field in the view (e.g.,
@Html.TextBoxFor(x => x.Age)) and then using JavaScript to show only one depending on the user category.My plan was to submit only the visible input fields so that the server is not confused about which input fields to use to create the model.
Unfortunately, Visual Studio doesn't quite play along: First, there's there problem of having multiple input field with the same
id; I could maybe live with that. But then, validation attributes in the HTML-source are generated only for the first occurrence of each data field in the view (e.g.,@Html.TextBoxFor(x => x.Age)), not for any later occurrences.
E.g., the first occurrence generates
<input data-val="true" data-val-number="The field Age must be a number."
data-val-range="The field Age must be between 10 and 99." data-val-range-max="99"
data-val-range-min="10" id="Age" name="Age" type="text" value="">
The second occurrence generates merely
<input id="Age" name="Age" type="text" value="">
How can I solve this? My thinking:
- Create all input fields hidden once at the beginning of the view and use Javascript to generate at the form dynamically. Downside: A lot of work, all page structure is now in JavaScript instead of view.
- Use partial views for different user categories. Downside: When the form page is opened (in the controller), I retrieve several lists from the database and put them in the model in order to populate the form DropDown input fields and RadioButton input lists in the view. Is there any way to reuse this information in the partial views so that there are not many repetitive database queries?
Any thoughts on the situation are very much appreciated. I'm somewhat new to ASP.NET MVC.