我需要为我的领域实现独特的验证检查
[Key]
[Required]
[DisplayName("Tag")]
public string Tag { get; set; }
错误此标签已存在...
最佳答案
为此,您可以使用远程验证规则。添加此规则 [Remote("IsTagAvailble", "MyController", ErrorMessage = "Tag Already Exist.")]
到您的标签字段。你的新代码将是
[Key]
[Required]
[DisplayName("Tag")]
[Remote("IsTagAvailble", "MyController", ErrorMessage = "Tag Already Exist.")]
public string Tag { get; set; }
第一个参数是操作名称,第二个参数是您的 Controller 名称,第三个参数是要显示给用户的错误文本。
现在在您的 Controller 中定义这个新操作,例如示例中的 MyController。
public class MyController : Controller
{
public ActionResult IsTagAvailble(string Tag)
{
using (DataBaseContext db = new DataBaseContext())
{
try
{
var tag = db.TABLE_NAME.Single(m => m.Tag == Tag);
return Json(false, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
}
}
这将使用不显眼的 javascript 远程验证 Tag 字段的唯一性并向用户显示错误。
最后你的观点应该是这样的
@Html.TextBoxFor(m => m.Tag) @Html.ValidationMessageFor(m => m.Tag)
关于entity-framework - 唯一字段 mvc 的客户端验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18037292/