c# - 两个属性具有相同的功能,只使用一种远程验证方法

标签 c# asp.net

是否可以在提供相同功能的两个属性中仅使用一种方法进行远程验证?例如,我有两个用于存储电子邮件的属性:第一个属性将只获取没有扩展名的电子邮件地址(例如 [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/

相关文章:

c# - 是否可以将 LINQ "Take"扩展方法的结果转换为原始类型?

c# - 如何用增量数字替换之前包含一些字符的唯一字符串

javascript - Access-Control-Allow-Headers Google map 地理编码不允许请求 header 字段授权

c# - 使用 where 语句的 Linq to NHibernate 包装器问题

c# - 上传带有附加信息的文件(Angular 8 到 C# Core 3)

c# - ASCII编码和编码之间的区别

c# - 连接和 Url 编码字符串时 Base-64 字符串中的无效字符

c# - 如何在不在每个过程中创建附加参数的情况下将线程文化从应用程序传递到 sql server?

asp.net - 在 Asp.Net 动态数据应用程序中使用 DisplayColumnAttribute 按多个字段排序?

Asp.NET ReportViewer::PDF Export = System.DllNotFoundException: 无法加载 DLL 'T2Embed' : 访问被拒绝