是否可以在提供相同功能的两个属性中仅使用一种方法进行远程验证?例如,我有两个用于存储电子邮件的属性:第一个属性将只获取没有扩展名的电子邮件地址(例如 [name]@email.com);第二种是获取完整的电子邮件地址(例如 [name@email.com])。
型号:
[MaxLength(50), Display(Name = "Email Address.")]
[Remote("CheckExistingEmail", "Account", AdditionalFields = "EmailExtension", ErrorMessage = "Email already exists")]
public string EmailWithoutExtension { get; set; }
[Email, MaxLength(100), Display(Name = "Email Address")]
[Remote("CheckExistingEmail", "Account", ErrorMessage = "Email already exists.")]
public string EmailWithExtension { get; set; }
[HiddenInput]
public string EmailExtension { get; set; }
Controller :
[AjaxOnly, AllowAnonymous]
public ActionResult CheckExistingEmail(string EmailWithExtension)
{
if(string.IsNullOrEmpty(EmailWithExtension))
{
return Json(true, JsonRequestBehavior.AllowGet);
}
var userEmail = AccountManager.FindByEmail(EmailWithExtension);
if (userEmail == null)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
return Json(false, JsonRequestBehavior.AllowGet);
}
我尝试为这两个属性重载方法,但不起作用,因为这会混淆远程验证。我也在考虑将属性绑定(bind)到一个变量中,但不确定我将如何做到这一点。关于如何在不创建具有相同功能的不同方法名称的情况下完成此操作的任何建议?
最佳答案
我知道怎么做了。因此,我只需添加所有参数并检查哪个参数具有值,然后验证该值。
[AjaxOnly, AllowAnonymous]
public ActionResult CheckExistingEmail(string emailWithoutExtension, string emailWithExtension, string emailExtension)
{
if(string.IsNullOrEmpty(emailWithoutExtension) && string.IsNullOrEmpty(EmailWithExtension))
{
return Json(true, JsonRequestBehavior.AllowGet);
}
var email = string.Emtpy;
if(!string.IsNullOrEmpty(emailWithoutExtension)) && !string.IsNullOrEmpty(emailExtension))
{
email = emailWithoutExtension + emailExtension;
}
if(!string.IsNullOrEmpty(emailWithExtension) && string.IsNullOrEmpty(emailWithoutExtension))
{
email = emailWithExtension;
}
var account = AccountManager.FindByEmail(email);
if (account == null)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
return Json("Email already exists try another.", JsonRequestBehavior.AllowGet);
}
通过执行上述代码,两个属性将只使用一种方法。
关于c# - 两个属性具有相同的功能,只使用一种远程验证方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39308404/