使用构造函数初始化MVC模型属性

时间:2015-05-21 03:52:16

标签: c# asp.net-mvc

我有一个MVC模型。

public class ProtocolSummary
{
    public string MasteredTask { get; set; }
    public string NewTask { get; set; }

    public List<AssistTech> ATList { get; set; }
}

public class AssistTech
{
    public string Type { get; set; }
    public string ScheduleForUse { get; set; }
    public string StorageLocation { get; set; }
}

如何使用构造函数初始化它?

2 个答案:

答案 0 :(得分:2)

MVC模型只是一个POCO。您可以使用默认构造函数初始化它并设置属性。或者更好地使用对象初始值设定项

// Assuming you want an instance of ProtocolSummary
 var protocolSummary = new ProtocolSummary()
{
    MasteredTask = "Some Mastered task name",
    NewTask = "Here goes new task"
};

这就是你想要的吗?

答案 1 :(得分:0)

我会尝试让Varinder Singh的答案更加完整:

// Assuming you want an instance of ProtocolSummary
var protocolSummary = new ProtocolSummary()
{
MasteredTask = "Some Mastered task name",
NewTask = "Here goes new task",
ATList  = new List<AssistTech>() 
{
new AssistTech() { Type  = "Some text", ScheduleForUse  = "Some other text", StorageLocation  = "Some other other text" },
new AssistTech() { Type  = "Some text", ScheduleForUse  = "Some other text", StorageLocation  = "Some other other text" }
}
};