我正在开发一个 Asp.Net MVC 4 应用程序,我有这两个模型类:
公司型号:
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>
当我创建新人员时,在 PersonController 上尝试保存时,我得到 ModelState.Isvalid = False,消息是“输入公司名称”。我不知道为什么会这样。
任何人都可以帮助我吗?
编辑
如果我将我的属性从 model.BcoID.CompanyID 更改为 model.BcoID.Name 并且我使用 EditorFor,而不是使用 DropDownListFor。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>