Remote validation preventing data editing

Asked

Viewed 238 times

2

I am using remote validation to prevent repeated emails in the database, which works well, when I do some registration. The problem is that the remote does not accept the original registration value, and does not allow me to save the changes made in the other fields. I saw a possible solution saying to pass the ID in a hidden text box, but it also didn’t work.

My Editing Action.

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Editar(Usuarios usuario) 
    {

        ViewBag.CountryList = p.GetCountries();
        if (ModelState.IsValid)
        {
            db.Entry(usuario).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index", "Home");
        }
        return View(usuario);
    }

Method that checks the Email.

public JsonResult validaEmail(string email)
        {
            return Json(!db.Usuarios.Any(u => u.Email == email), JsonRequestBehavior.AllowGet);
        }

[Required(ErrorMessage = "Campo Obrigatório")]
[Display(Name = "E-mail")]
[Remote("validaEmail", "Validar",AreaReference.UseRoot,ErrorMessage = "E-mail já existente. Por favor, utilize outro E-mail")]
[EmailAddress]
public string Email { get; set; }
  • Shows how you call the client to validate the email.

  • I edited it. Check it out, please.

  • Test there and tell me if the remote validation is passing the id. Sds.

1 answer

6


Has to pass the id even otherwise you won’t be able to change the object. It will look something like this:

public JsonResult validaEmail(string email, int id)
{
    return Json(!db.Usuarios.Any(u => u.Email == email && i.Id != id), JsonRequestBehavior.AllowGet);
}

I think that solves:

[Remote("validaEmail", "Validar", AdditionalFields = "Id", AreaReference.UseRoot,ErrorMessage = "E-mail já existente. Por favor, utilize outro E-mail")]

I did a test here and it worked like this (you can see the tutorial and download the project zipped in http://blogdoquintal.net/2015/01/06/fazendo-validacao-ajax-no-servidor-com-asp-net-mvc/

Homecontroller (will always return false to the tests):

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult About()
    {
        ViewBag.Message = "Your application description page.";
        return View();
    }

    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";

        return View();
    }

    public ActionResult EmailDisponivel(int? Id, string email)
    {
        return Json(false, JsonRequestBehavior.AllowGet);
    }
}

Model:

public class Usuario
{
    public int? Id { get; set; }
    [Required(ErrorMessage="Campo obrigatório")]
    public string Nome { get; set; }
    [Required(ErrorMessage = "Campo obrigatório")]
    [EmailAddress(ErrorMessage="Email inválido")]
    [Remote("EmailDisponivel", "Home", AdditionalFields = "Id", ErrorMessage = "E-mail já existente. Por favor, utilize outro E-mail")]
    public string Email { get; set; }
}

View (the view code for html will get all weird but it’s kind of like that:

@model ValidacaoRemota.Models.Usuario

@{
    ViewBag.Title = "Index";
}

Index

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
    <h4>Usuario</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.Id)

    <div class="form-group">
        @Html.LabelFor(model => model.Nome, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Nome, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Nome, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </div>
</div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
  • So he stopped checking the Email field, but I still can’t save the edits.

  • In fact, not even give the post. I’ll add you.

  • I’ll try to do a project here and send you

  • What is this Areareareareference.Useroot for? I don’t know.

  • Here worked cool. I’ll pass you the project items

  • Look there. I only took this Areareareference.UseRoot. I will create a tutorial on my blog and send you the link. There I put the project to download.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.