rpmansion rpmansion - 2 months ago 7
ASP.NET (C#) Question

two properties serve the same function to use only one remote validation method

It is it possible to use only one method, for Remote validation, in two properties that serve the same functionality? For instance I have two properties used to store email: the first property will only get the email address that does not have an extension (e.g. [name]@email.com); the second one is to get the whole email address (e.g. [name@email.com]).

Model:

[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);
}


I tried method overloading for the two properties which did not work because this confuse the remote validation. I'm also thinking to bind the properties in one variable but not sure how I'm going to do that. Any suggestion on how I can accomplish this without creating different method name that serves the same functionality?

Answer

I figured out how to do it. So I just have to add all of the parameters and check which one has the value then validate the value.

[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);
}

By doing the above codes, both properties will just use one method.