Asp.Net MVC 4 アプリケーションを開発しています。次の 2 つのモデル クラスがあります。
会社のモデル:
Public Class CompanyModel
<Key()>
Public Overridable Property CompanyID As Integer
<Required(ErrorMessage:="Enter a company name.")>
<Display(Name:="Company")>
<StringLength(80, ErrorMessage:="The {0} must have {2} characters.", MinimumLength:=2)>
Public Overridable Property Name As String
<Required(AllowEmptyStrings:=False, ErrorMessage:="Enter the DB ID.")>
<Display(Name:="DB ID")>
Public Overridable Property DBID As Integer
End Class
人物モデル:
Public Class PersonModel
<Key()>
Public Overridable Property PersonID As Integer
<Required(AllowEmptyStrings:=False, ErrorMessage:="Enter the name.")>
<Display(Name:="Name")>
Public Overridable Property Name As String
<Required(AllowEmptyStrings:=False, ErrorMessage:="Enter the pass")>
<DataType(DataType.Password)>
<Display(Name:="Password")>
Public Overridable Property Password As String
<Required(AllowEmptyStrings:=False, ErrorMessage:="Enter the mail")>
<Display(Name:="E-mail")>
Public Overridable Property Email As String
<Required(ErrorMessage:="Enter the company")>
<Display(Name:="Company")>
Public Overridable Property BcoID As CompanyModel
End Class
パーソンコントローラー:
'
' POST: /Person/Create
<HttpPost()> _
Function Create(ByVal model As PersonModel) As ActionResult
Try
If ModelState.IsValid Then
personDAO.Save(model)
End If
Return RedirectToAction("Index")
Catch
Return View()
End Try
End Function
Views/Person/Create に次のコードがあります。
<div class="editor-label">
@Html.LabelFor(Function(model) model.BcoID)
</div>
<div class="editor-field">
@Html.DropDownListFor(Function(model) model.BcoID.CompanyID, New SelectList(ViewBag.Company, "CompanyID", "Name"))
@Html.ValidationMessageFor(Function(model) model.BcoID)
</div>
新しい Person を作成しているときに、保存しようとすると PersonController で ModelState.Isvalid = False が表示され、メッセージは「会社名を入力してください」です。なぜそれが起こるのかわかりません。
誰でも私を助けることができますか?
編集
プロパティを model.BcoID.CompanyID から model.BcoID.Name に変更し、DropDownListFor を使用する代わりに EditorFor を使用するとします。ModelState.IsValid は True ですが、DropDownList が必要なので、DropDownList を配置すると、ビューに検証メッセージ (「会社には 2 文字が必要です」) が表示されます。
これが私が今持っているものです:
<div class="editor-label">
@Html.LabelFor(Function(model) model.BcoID.Name)
</div>
<div class="editor-field">
@Html.DropDownListFor(Function(model) model.BcoID.Name, New SelectList(ViewBag.Company, "CompanyID", "Name"))
@Html.ValidationMessageFor(Function(model) model.BcoID.Name)
</div>