简体   繁体   English

动态将字段添加到C#类并在MVC剃刀中用作模型

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

I have a class named Agent: 我有一个名为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: 10秒后,数据表将具有:

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. 我想每次在“运行时”将动态属性添加到类“ Agent”。 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. 创建它之后,我想给MVC视图类“ Agent”作为它的模型。 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. 您的Agent类应具有一个名为Name的字符串属性,其中包含代理的名称(例如,“ Dexter”,“ Jordon”等)。如果Measure属性包含诸如“ Logins / hour”之类的值,则您可能需要一个Value属性,其中包含值,例如“ 9.6”,“ 5.5”等。

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. 然后,将使用数据库中的代理记录填充您的代理数据表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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