我正在开发一个Asp.Net MVC 4应用程序,我有两个模型类:
CompanyModel:
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
PersonModel:
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
PersonController:
'
' 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并使用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>
答案 0 :(得分:0)
确保您的视图中有公司名称属性,因为您的模型中需要此属性:
<div class="editor-label">
@Html.LabelFor(Function(model) model.BcoID.Name)
</div>
<div class="editor-field">
@Html.EditorFor(Function(model) model.BcoID.Name)
@Html.ValidationMessageFor(Function(model) model.BcoID.Name)
</div>
Label和ValidationMessage帮助程序也附加到CompanyID属性的错误属性。它应该是这样的:
<div class="editor-label">
@Html.LabelFor(Function(model) model.BcoID.CompanyID)
</div>
<div class="editor-field">
@Html.DropDownListFor(Function(model) model.BcoID.CompanyID, New SelectList(ViewBag.Company, "CompanyID", "Name"))
@Html.ValidationMessageFor(Function(model) model.BcoID.CompanyID)
</div>
注意Label和ValidationMessage现在如何与DropDownList正确关联。