2015-03-25 27 views
0

我试图添加一个字典属性在我的模型类中有一个键值对的集合列表之一。但是,我不知道如何用{get; set;}语法表示这是一个模型属性,而不是一个简单的字段。在ASP.NET MVC中声明初始化字典模型属性的语法?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 

namespace ContosoUniversity.Models 
{ 
    public class Profile 
    { 
    //classNameID or ID is interpreted by EF as PK. 
    public int ID { get; set; } 
    public string UserName { get; set; } 
    public string Age { get; set; } 
    public string Location { get; set; } 
    public string Gender { get; set; } 

    //How to declare this property with get, set and initialized key/val pairs? 
    public string Dictionary<string, string> ProfileDetails = 
     new Dictionary<string, string>() 
     { 
      {"HighSchool", ""}, 
      {"UndergraduateSchool", ""}, 
      {"GraduateSchool", ""}, 

     } 
    } 

}

回答

5

声明属性和您可以使用构造函数来初始化它。

public class Profile 
{ 

    public Dictionary<string, string> ProfileDetails {get; set;} 

    public Profile() 
    { 
     ProfileDetails = new Dictionary<string, string>() 
     { 
      {"HighSchool", ""}, 
      {"UndergraduateSchool", ""}, 
      {"GraduateSchool", ""}, 

     }; 
    } 
} 
+0

噢非常感谢你,忘记了一切都是“班级”甚至是模特班! – jerryh91 2015-03-25 03:33:35

0

宣言:

class Profile{ 
    private Dictionary<string,string> _profileDetails; 
    public Dictionary<string,string> ProfileDetails { get { return _profileDetails; } } 
    public Profile() { _profileDetails = new Dictionary<string,string>(); } 
} 

用法:

var myProfile = new Profile(); 
myProfile.ProfileDetails["key2"] = "Something"; 
0
public Dictionary<string, string> ProfileDetails {get; set}; 

//自动属性的语法。该属性将由相同类型的字段自动支持,即字典

对于初始化,使用类构造函数在其中添加keyValuePairs。

public Profile() 
{ 
    ProfileDetails = new Dictionary<string, string>(){ 
     {"key01", "value01"}, 
     {"key02", "value02"}, 
     {"key03", "value03"} 
    }; //This syntax is called collection initializer. 
} 

以这种方式,你可以在这里实现你的目标。