Remote Validation in ASP.Net MVC 3: How to use AdditionalFields in Action Method

Strange. It works for me:

Model:

public class MyViewModel
{
    [Required]
    [Remote("IsEmailAvailable", "Home", AdditionalFields = "InitialEmail")]
    public string Email { get; set; }
}

Controller:

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

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }

    public ActionResult IsEmailAvailable(string email, string initialEmail)
    {
        return Json(false, JsonRequestBehavior.AllowGet);
    }
}

View:

@model AppName.Models.MyViewModel
@{
    ViewBag.Title = "Home Page";
}
<script src="https://stackoverflow.com/questions/4752877/@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="https://stackoverflow.com/questions/4752877/@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
    @Html.TextBoxFor(x => x.Email)
    @Html.ValidationMessageFor(x => x.Email)
    <input type="hidden" name="InitialEmail" value="foo@bar.com" />
    <input type="submit" value="OK" />
}

IIRC there was some bug in ASP.NET MVC 3 RC2 with this remote validation that was fixed in the RTM.

Leave a Comment