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")
}
Shows how you call the client to validate the email.
– Marco Antonio Quintal
I edited it. Check it out, please.
– Ryan Santos
Test there and tell me if the remote validation is passing the id. Sds.
– Marco Antonio Quintal