I use Remote attribute on my ViewModel in ASP.NET MVC 4 application. Here is my simple model:
public class User
{
[Required(AllowEmptyStrings = false, ErrorMessage = "test test")]
public int Id { get; set; }
[DisplayName("Email")]
[Remote("RemoteValidateEmailLengthValidation", "Home")]
public string Email { get; set; }
}
And remote validation method:
public JsonResult RemoteValidateEmailLengthValidation(string Email)
{
if (Email.Length > 20)
{
return Json("Too long email", JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
I added all scripts that i need for validation on Layout:
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")
@Scripts.Render("~/bundles/jqueryval")
Write all that i need for validation in WebConfig:
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
And add simple Controller that creates empty model and return View.
@model ViewModels.User
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("PostUser", "Home", FormMethod.Post))
{
@Html.EditorForModel()
<input type="submit" />
}
It works only if i wrap my model in form and doesn't work if i write my View like this:
@model ViewModels.User
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
@Html.EditorForModel()
So i have questions:
- Why remote validation doesn't work without form? Because in Chrome debugger i see that form don't submit i see only Validation method call.
- Which javascript method used by Remote validation?
OnChange? Can i see it anywhere and can i change it?
@when it is within theusingclausedata-val-*attributes necessary for jquery unobtrusve validation are not rendered unless the html helper is generated inside a form so the method will never be called (this is by design). Why would you want to change the method?OnFocus.jquery.validate.jsandjquery.validate.unobtrusive.jsopen it and search "remote" (its about 3/4 down both files) But there is nothing you can change to make this work outside a form. All the method does it make a $.getJSON()` call, so you can always do that manually and render the message