I will explain this idea in a short example. We have the "IsMasterProject" flag to set in the "MasterProjectNo" field:
To accomplish the required “on the fly” you will need the following things:
Define your model using a field that is not strict. [Required]
class ProjectList { public bool IsMasterProject { get; set; }
Create a view with an example field code:
<div class="data-field"> <div class="editor-label"> <div id="IsMasterProjectLabel"> Is Master Project </div> </div> <div class="editor-field"> <input id="IsMasterProject" class="check-box" type="checkbox" value="true" name="IsMasterProject" data-val-required="The IsMasterProject field is required." data-val="true" checked="checked"> </div> </div> <div class="data-field"> <div class="editor-label"> <div id="MasterProjectNoLabel"> Master Project No </div> </div> <div class="editor-field"> <input id="MasterProjectNo" type="text" value="" title="" style="width: 9.2em" placeholder="" name="MasterProjectNo" maxlength="15" data-val-length-max="15" data-val-length="The field MasterProjectNo must be a string with a maximum length of 15." data-val="true"> </div> </div>
Add Java Script to handle the click code and add or remove the “required” label:
$(function () { $("#IsMasterProject").change(function () { OnIsMasterProjectValueChange(); }); OnIsMasterProjectValueChange(); }); function OnIsMasterProjectValueChange() { if ($('#IsMasterProject').is(':checked')) { $('#IsMasterProjectLabel').append('<span class="label-required">*</span>'); } else { $('#IsMasterProjectLabel span').remove() } };
In the controller, you can prepare the show action:
[Authorize] public ActionResult Edit(int id) { try { ProjectList project = prepare_ProjectList(id); return View(project); } catch (Exception ex) { sysHelper.LogError(ex, ModelState); ModelState.AddModelErrorException(ex, Request, "Probably selected data doesn't exist."); return View("Error"); } }
In the save action, you can check the necessary conditions:
[HttpPost] public ActionResult Edit(ProjectList project) { try { if (ModelState.IsValid) { if (project.IsMasterProject && string.IsNullOrEmpty(project.MasterProjectNo)) { ModelState.AddModelError("Model", "The MasterProjectNo field is required."); } else { project.UserID = CurrentUser.ID; project.C_updated = DateTime.Now; db.ProjectList.Attach(project); db.Entry<ProjectList>(project).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } } } catch (Exception ex) { sysHelper.LogError(ex, ModelState); ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator."); } prepareViewBag(project); return View(project); }
It works like a charm :) Good luck.