I have applied remote validation on multiple fields based on the answer of this question on year and section fields to ensure a user will not enter same section in same year but it is not show any validation message
Model (auto generated from database but I have added [Remote]
and [Required]
)
[Required]
public Nullable<short> Year { get; set; }
[Required]
[Remote("IsSectionAvailable", "Test", AdditionalFields = "Year", ErrorMessage = "Value is not valid")]
public string Section { get; set; }
the function in Controller
[AllowAnonymous]
[HttpPost]
public ActionResult IsSectionAvailable(string Section,short Year)
{
try
{
return Json(!IsSectionExists(Section,Year));
}
catch (Exception ex)
{
return Json(false);
}
}
ITDBEntities1 db = new ITDBEntities1();
private bool IsSectionExists(string Section, short Year)
{
// Query for all projects with section
var project = from s in db.SeniorProject
where s.Section==Section
select s;
var Y = from s in db.SeniorProject
where s.Year == Year
select s;
if (project.Any()&&Y.Any())
{
return true;
}
return false;
}
form in View
@model Testinggggg.Models.SeniorProject
....
@using (Html.BeginForm())
{
@Html.ValidationSummary(true);
@Html.LabelFor(model => model.Section)
@Html.EditorFor(model => model.Section)
@Html.ValidationMessageFor(model => model.Section)
@Html.LabelFor(model => model.Year)
@Html.EditorFor(model => model.Year)
@Html.ValidationMessageFor(model => model.Year)
}
The view includes
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>