我在MVC3中阅读了这个有用的例子http://msdn.microsoft.com/en-us/library/gg508808%28v=vs.98%29.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2进行远程验证,当我创建一个新项目时,它很有用;但是,当我尝试编辑新创建的项目时,我遇到了麻烦。
我有这样的模型
Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations
Imports System.Web.Mvc
Imports System.Collections.Generic
Public Class Language
Public Property LanguageId As Integer
<Display(Name:="DisplayNameLanguageName", ResourceType:=GetType(Resources.Language)),
Required(ErrorMessageResourceName:="ErrorMessageLanguageNameRequired", ErrorMessageResourceType:=GetType(Resources.Language)),
StringLength(20),
Remote("IsNameAvailable", "Language", "AdminArea", ErrorMessageResourceName:="ErrorMessageNameNotAvailable", ErrorMessageResourceType:=GetType(Resources.Language))>
Public Property Name As String
Public Property Flag as String
End Class
在Controller“语言”课程中,我有......
'OutputCache needed for remote validation
<OutputCache(Location:=OutputCacheLocation.None, NoStore:=True)>
Public Class LanguageController
Inherits System.Web.Mvc.Controller
Private db As StoreEntities = New StoreEntities
'remote validation for duplicates
Public Function IsNameAvailable(Name As String) As JsonResult
Return Json(Not db.Languages.Any(Function(x) x.Name = Name), JsonRequestBehavior.AllowGet)
End Function
[...]
从“Create.vbhtml”视图中,我可以创建一种新语言,但是从“Edit.vbhtml”我不能仅编辑Flag属性,因为验证开始时为Name保留相同的值。我也被迫改变了Name属性。
我该如何解决这个问题?
答案 0 :(得分:0)
我解决了在Edit.vbhtml视图中添加隐藏字段“HiddenName”并将语言名称作为值的问题,并在Controller中编辑验证函数
Public Function IsNameAvailable(Name As String, Optional HiddenName As String = "") As JsonResult
If Name <> HiddenName Then
Return Json(Not db.Languages.Any(Function(x) x.Name = Name), JsonRequestBehavior.AllowGet)
Else
Return Json(True, JsonRequestBehavior.AllowGet)
End If
End Function