2012-01-23 5 views
0

を結合私は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; } 
} 

と私のメインRegister.cshtmlで

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

で構成RegisterModelを持って、私はこのようなそれぞれの質問が含まれていない:

@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つの質問は、1として振る舞う:私は第一秘密の質問の答えに質問や種類を選択した場合、他の言葉で、彼らはすべての検証、およびその逆を渡す...

はまた、HttpPost Registerメソッドに投稿するに

public ActionResult Register(RegisterModel model) { ... 

model.SecretQuestion1は常にnullです。それらのすべてがあります。このようなネストされたモデルバインドをどうやってやっていますか?私はこれがうまくいくと思った。

答えて

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 - 理由は、部分的なビューは同じ名前の2つの異なるプロパティを処理する方法を知らないからです。 –

+0

ハ!それは、感謝@MystereManだった。私は今あなたを愛しています –

関連する問題