0

我试图在“安全问题”的用户注册期间溺水。

SecurityQuestion我的 ViewModel 上的属性应该是一个字符串(只保存选定的问题)还是IEnumerable<string>保存整个问题列表?在后一种情况下,POSTed 的模型如何知道选择了哪个?

取决于哪个是更好的方法,显示 html 下拉列表并预先选择最顶部的项目的代码是什么(这是必填字段,因此不应选择“空白”)?

另外,我将使用 ajax 提交此表单。在前一种情况下,我可以使用option:selected选择器将所选问题附加到string模型上的 SecurityQuestion 属性中。但我不明白在后一种情况下它是如何工作的(IEnumerable<string>在模型上使用 an 作为属性)

4

1 回答 1

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?"}
            };
    }

然后做了一个这样的ajax帖子:

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

jQuery 序列化方法为安全问题发送所选项目的“值”。我想要实际的问题,这就是为什么我将 Value 和 Text 设置为相同的东西,否则你可以设置它,以便在选择项目时你想要获得的任何值。

于 2012-12-19T01:42:49.793 回答