简体   繁体   中英

Add fields dynamically to a C# Class and use in MVC razor as model

I have a class named Agent:

public class Agent
{
    public string Measure { get; set; }
}

I have a Datatable, whose columns are dynamic (different every time from database except "Measure" column)

For Example:

Measure    |     Dexter     |     Jordon     |     Ana     |     Polark     |
Login hour        8.7              5.5             7.5            4.8

After 10 seconds, the Datatable will have:

Measure    |     Robert     |      Leo       |    Black    |     Operah     |
Login hour        9.6              5.5             4.3            4.8

When the datatable is created. I want to add dynamic properties to the class "Agent" at "Runtime" each time. It should become:

public class Agent
{
    public string Measure { get; set; }
    public string Dexter { get; set; }
    public string Jordon { get; set; }
    public string Ana { get; set; }
    public string Polark { get; set; }
}

After it is created, I want to Give the class "Agent" to the MVC View as its model. How I can achieve this.

Note: I am a beginner, so please help me out. I can,t find the solution anywhere.

I don`t think you can add things that way dynamically, but perhaps you can use a dictionary instead:

public class Agent
{
    public string Measure { get; set; }
    public Dictionary<string, string> Scores {get; set;}    
}

Then you can add and get stuff from it like:

instanceOfAgent.Scores.Add("Rob", "9.6");
instanceOfAgent.Scores.Add("John", "4.8");
...

var johnsScore = instanceOfAgent.Scores["John"]; // will return "4.8"

This is not a good way to solve the problem.

Your Agent class should have a string property called Name that holds the name of the Agent (eg "Dexter", "Jordon" etc) If your Measure property contains a value like "Logins/hour" then you probably need a Value property that contains values such as "9.6", "5.5" etc.

One Agent object then holds the Name, Measure and Value for one Agent.

Your Agent DataTable is then populated with Agent records from the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM