2012-12-19 70 views
0

我試圖在用戶註冊「安全問題」期間淹沒一滴水。SecurityQuestion DropDownList - 預定義項目

我的ViewModel上的SecurityQuestion屬性應該是一個字符串(僅保存所選問題)還是IEnumerable<string>來保存整個問題列表?在後面的例子中,POST的模型怎麼知道選擇了哪一個?

取決於哪個更好的方法將顯示HTML下拉列表和預先選擇最上面的項目(這是一個必填字段,所以「空白」不應該是可選的)的代碼是什麼?

另外,我將使用ajax提交此表單。在前一種情況下,我可以使用option:selected選擇器將所選問題附加到我的模型上的string SecurityQuestion屬性。但我不明白它是如何工作在後一種情況下(與IEnumerable<string>作爲模型的財產)

回答

1

好吧,明白了這一點。我用了一個字符串類型來保存剛纔所選擇的安全問題和答案:

public class RegisterFormViewModel 
{ 
    ... 

    [Required] 
    [Display(Name = "Security Question")] 
    public string SecurityQuestion { get; set; } 

    [Required] 
    [Display(Name = "Security Answer")] 
    public string SecurityAnswer { get; set; } 

    ... 
} 

然後填充列表如下:

@Html.DropDownListFor(m => m.SecurityQuestion, QuestionHelper.GetSecurityQuestions()) 

使用這個幫手:

public static IEnumerable<SelectListItem> GetSecurityQuestions() 
    { 
     return new[] 
      { 
       new SelectListItem { Value = "What was your childhood nickname?", Text = "What was your childhood nickname?"}, 
       new SelectListItem { Value = "What is the name of your favorite childhood friend?", Text = "What is the name of your favorite childhood friend?"}, 
       new SelectListItem { Value = "What school did you attend for sixth grade?", Text = "What school did you attend for sixth grade?"}, 
       new SelectListItem { Value = "In what city or town did your mother and father meet?", Text = "In what city or town did your mother and father meet?"}, 
       new SelectListItem { Value = "What is the first name of the boy or girl that you first kissed?", Text = "What is the first name of the boy or girl that you first kissed?"}, 
       new SelectListItem { Value = "What is the name of a college you applied to but didn't attend?", Text = "What is the name of a college you applied to but didn't attend?"}, 
       new SelectListItem { Value = "Where were you when you first heard about 9/11?", Text = "Where were you when you first heard about 9/11?"}, 
       new SelectListItem { Value = "What is your grandmother's first name?", Text = "What is your grandmother's first name?"}, 
       new SelectListItem { Value = "What was the make and model of your first car?", Text = "What was the make and model of your first car?"}, 
       new SelectListItem { Value = "In what city and country do you want to retire?", Text = "In what city and country do you want to retire?"} 
      }; 
    } 

然後做了一個阿賈克斯職位是這樣的:

$.post('/Account/Register', $('#registerForm').serialize(), function(){ //success }); 

jQuery序列化方法發送安全問題所選項目的「值」。我想要的是真正的問題,這就是爲什麼我將Value和Text設置爲相同的東西,否則您可以將它設置爲任何想要獲取的值(如果選擇該項目)。