2015-03-25 56 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. 
} 

以這種方式,你可以在這裏實現你的目標。