Hill Hill - 1 year ago 148
C# Question

How to dynamically loop through field names in an MVC Data Model?

In my database structure, I have an array of fields for a particular user. Like...

User: Choice1, Choice2, Choice3, Choice4, etc.

When the View is posted to the controller, the values that will go into those fields are passed in a string array (
) from a dynamically constructed set of hidden inputs.

My brilliant idea was to use a
loop to go through the array and assign the values. So, something like:

for (int x = 0; x < MyChoices.Count(); x++ {
model.Choice[x + 1] = MyChoices[x];

But, I'm not having any luck figuring out how to dynamically get the field names out of the model so that I can assign them.

Essentially I'm looking for something like:
model.GetField("Choice" + x + 1)

Is there any way to do this? I was thinking about reforming my data structure so that, instead of listing out Choice1, Choice2, Choice3, etc., I just have a Choices table that lists User, ChoiceID, ChoiceValue. But, I really don't wanna restructure my data, because I have another page where it's actually laid out in a table. Is there a way to do this, or am I just breaking every Database/Developer commandment there is?

I know this is a fairly "How do you do this" type question, but I've been searching and haven't really found a solution... and I'm actually looking for C# syntax, so I think it qualifies.

Here is the Model class:

public partial class UserChoice
public int UserChoiceID { get; set; }
public Nullable<int> UserID { get; set; }
public string User { get; set; }
public string Choice1 { get; set; }
public string Choice2 { get; set; }
public string Choice3 { get; set; }
public string Choice4 { get; set; }
public string Choice5 { get; set; }
public string Choice6 { get; set; }
public string Choice7 { get; set; }
public string Choice8 { get; set; }
public string Choice9 { get; set; }
public string Choice10 { get; set; }
public string Choice11 { get; set; }
public string Choice12 { get; set; }
public string Choice13 { get; set; }
public string Choice14 { get; set; }
public string Choice15 { get; set; }
public string Choice16 { get; set; }

Answer Source

Alrighty, here's how I did it:

First off, hats off to Halford... I mean, @Thorarins, because he pretty much led me in the right direction. Essentially, I was able to accomplish my task with the following:

for (int x = 0; x < MyChoices.Count(); x++)
    td.GetType().GetProperties().Single(p => p.Name == "Choice" + (x + 1)).SetValue(td, MyChoices[x]);

My end solutions here seem a little clunky and unnatural. So, if anyone has any good ideas how to make it better, I'm all ears.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download