我將解釋在很短的例子的想法。我們有「IsMasterProject」來設置所需的「MasterProjectNo」字段的複選框:
要做到「對飛」,你需要下面的東西需要:
定義與現場模型,這是不嚴格[必填]
class ProjectList {
public bool IsMasterProject { get; set; }
// this field will be optionally required,
// we do not need the [Required] attribute
public string MasterProjectNo { get; set; }
}
創建的實例字段代碼視圖:
<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>
添加Java腳本來處理點擊代碼,並添加或刪除「requir ED」標記:
$(function() {
$("#IsMasterProject").change(function() { OnIsMasterProjectValueChange(); });
OnIsMasterProjectValueChange();
});
function OnIsMasterProjectValueChange() {
if ($('#IsMasterProject').is(':checked')) {
$('#IsMasterProjectLabel').append('<span class="label-required">*</span>');
}
else {
$('#IsMasterProjectLabel span').remove()
}
};
在控制器,你可以準備show動作:
[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");
}
}
在攢動,你可以驗證的狀況下,你需要:
[HttpPost]
public ActionResult Edit(ProjectList project)
{
try
{
if (ModelState.IsValid)
{
/* ------------------------------------------------------------------------ */
/* HERE YOU CAN ADD YOUR CODE TO CHECK THE FIELD */
/* ------------------------------------------------------------------------ */
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);
}
這很像一個魅力:) 祝你好運。