Validating data with mvc asp.net (editing)

0

I have a user registry where I use the remote validation in the data annotation to check if the user that is being registered already exists, my problem is in editing, how I am changing and using the same object the system thinks I am registering a new user and informs that I can not register because the registration informed already exists.

How do I make sure that when I'm editing the registry, it does not check for duplicity?

My template

            [DisplayName("E-mail")]
            [Required(ErrorMessage = "Favor informar o E-mail do usuário")]
            [Remote("Unico", "Usuario", ErrorMessage = "Esse e-mail já existe no sistema")]
            [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Favor informe um e-mail válido")]
            public string email{ get; set; }

And here I have the remote validation function

public ActionResult Unico(string email)
        {
            try
            {
                int idUsuario = 123;//Usuário/ADM de teste

                Models.user = bd.users.SingleOrDefault(s => s.email == email && s.idUsuario == idUsuario);
                bool retorno = false;
                if (c == null)
                {
                    retorno = true;
                }
                return Json(retorno, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(false, JsonRequestBehavior.AllowGet);
            }
        }
    
asked by anonymous 18.07.2014 / 01:08

2 answers

1

I've had this problem, but I did not use remote validation .

In my case, it occurred when receiving the object the ID was zero. So the persistence framework I was using understood that it was a new object to be registered.

Verify that your Action ID is being received.

If it is not, render this ID in the View (in an input hidden for example) so that it can be sent in the post for your Action.

If you are not in this situation, please edit the question by adding your Controller's code to try to help you.

    
18.07.2014 / 04:48
0

RemoteAttribute expects JsonResult , not ActionResult . Anything other than true it interprets as an error. This could be a misinterpretation.

public JsonResult Unico(string email)
{
    try
    {
        int idUsuario = 123;//Usuário/ADM de teste
        Models.user = bd.users.SingleOrDefault(s => s.email == email && s.idUsuario == idUsuario);
        if (c == null)
        {
            return Json(true, JsonRequestBehavior.AllowGet);
        }

        return Json(String.Format(CultureInfo.InvariantCulture,
            "O e-mail {0} já existe no sistema", email), JsonRequestBehavior.AllowGet);    
    }
    catch (Exception e)
    {
        return Json("Erro! " + e.Message, JsonRequestBehavior.AllowGet);
    }
}

With this you can simplify your [Remote] , with more error messages until:

[Remote("Unico", "Usuario")]

There are more examples here: link

    
18.07.2014 / 20:31