2012-01-23 17 views
0

我有一个RegisterModel,5个SecretQuestionAndAnswerModel模型嵌套MVC3模型既不证实也不结合

public class RegisterModel 
{ 
    public SecretQuestionAndAnswerModel SecretQuestion1 { get; set; } 
    public SecretQuestionAndAnswerModel SecretQuestion2 { get; set; } 
    public SecretQuestionAndAnswerModel SecretQuestion3 { get; set; } 
    public SecretQuestionAndAnswerModel SecretQuestion4 { get; set; } 
    public SecretQuestionAndAnswerModel SecretQuestion5 { get; set; } 
} 

public class SecretQuestionAndAnswerModel 
{ 
     public SecretQuestionTypeModel Type { get; set; } 

     [Required(ErrorMessage = "Please choose a question.")] 
     public int Id { get; set; } 
     public string Question { get; set; } 

     [Required] 
     [StringLength(20)] 
     public string Answer { get; set; } 

     [Display(Name = "Select Question")] 
     public IEnumerable<SelectListItem> DefaultQuestions { get; set; } 
} 

在我的主要Register.cshtml组成,包括我这样的每一个问题:

@Html.Partial("_QuestionAndAnswer", Model.SecretQuestion1, new ViewDataDictionary { { "Index", 1 }}) 

而且部分看起来像:

<div class="input"> 
     @{ 
      @Html.DropDownListFor(m => Model.Id, Model.DefaultQuestions, "(Please choose one)") 
      @Html.ValidationMessageFor(m => Model.Id) 

      @Html.TextBoxFor(m => m.Answer) 
      @Html.ValidationMessageFor(m => m.Answer) 
     } 
</div> 

但在验证,所有5个问题表现为一个:换句话说,如果我选择的第一个秘密的问题,然后他们都通过验证回答的问题和类型,反之亦然......

此外,在发布到HttpPost注册方法

public ActionResult Register(RegisterModel model) { ... 

的model.SecretQuestion1总是空。他们都是。你如何做这种嵌套的模型绑定?我认为这会工作正常。

回答

1

原因很明显,如果你看看生成的HTML。每个项目具有相同的ID和相同的名称。模型联编程序没有简单的方法来确定哪个是哪个。

这是部分视图和模板之间区别的主要示例。模板有额外的逻辑来处理这种情况。

你应该,而是创建一个SecretQuestionAndAnswerModel模板,并使用

@EditorFor(x => x.SecretQuestion1) 

如果您不确定的模板是如何工作的,这样说的:

http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html

+0

是的,我可以看到,在HTML ,但我想知道的是为什么它这样做。立即尝试编辑器模板,谢谢 –

+0

@RalphLavelle - 原因是部分视图不知道如何处理同名的两个不同属性。 –

+0

哈!就是这样,谢谢@MystereMan。我现在爱你 –

相关问题