我的页面上有3个必填字段,其中2个字段是隐藏的。隐藏字段值由jQuery根据下拉列表的选择填充。如果我只是将所有内容都留空以便没有填写所有字段并点击提交按钮,则@Html.ValidationSummery()
仅列出1个可见字段的错误。当隐藏字段没有值时,如何让它显示错误?
隐藏字段的代码:
<li>
<label for="SelectedProjects">Selected Projects:</label>
<select size="1" id="SelectedProjects" name="SelectedProjects" multiple="multiple"></select> <button class="removeButton" data-codetype="Project" type="button">-</button>
@Html.EditorFor(m => m.SelectedProjectCodes)
</li>
<li>
<label for="SelectedTasks">Selected Tasks:</label>
<select size="1" multiple="multiple" id="SelectedTasks" name="SelectedTasks"></select> <button class="removeButton" data-codetype="Task" type="button">-</button>
@Html.EditorFor(m => m.SelectedTaskCodes)
</li>
呈现的HTML:
<li>
<label for="SelectedProjects">Selected Projects:</label>
<select size="1" id="SelectedProjects" name="SelectedProjects" multiple="multiple"></select> <button class="removeButton" data-codetype="Project" type="button">-</button>
<input data-val="true" data-val-required="The SelectedProjectCodes field is required." id="SelectedProjectCodes" name="SelectedProjectCodes" type="hidden" value="" />
</li>
<li>
<label for="SelectedTasks">Selected Tasks:</label>
<select size="1" multiple="multiple" id="SelectedTasks" name="SelectedTasks"></select> <button class="removeButton" data-codetype="Task" type="button">-</button>
<input data-val="true" data-val-required="The SelectedTaskCodes field is required." id="SelectedTaskCodes" name="SelectedTaskCodes" type="hidden" value="" />
</li>
支持它的ViewModel中的属性:
[HiddenInput(DisplayValue = false), Required]
public string SelectedProjectCodes { get; set; }
[HiddenInput(DisplayValue = false), Required]
public string SelectedTaskCodes { get; set; }
答案 0 :(得分:1)
默认情况下,jQuery验证(这是MVC使用的)忽略隐藏字段。您可以通过在页面加载时更改默认设置来调整此项。一种方法是将类添加到隐藏字段以强制它们进行验证。
<li>
<label for="SelectedProjects">Selected Projects:</label>
<select size="1" id="SelectedProjects" name="SelectedProjects" multiple="multiple"></select> <button class="removeButton" data-codetype="Project" type="button">-</button>
<input class="force-validation" data-val="true" data-val-required="The SelectedProjectCodes field is required." id="SelectedProjectCodes" name="SelectedProjectCodes" type="hidden" value=""/>
</li>
更改默认值的javacript看起来像这样
jQuery.validator.setDefaults({
ignore: ":hidden:not(.force-validation)"
});