在我的視圖中我有一個dropdownlistfor。下拉列表有5個選項。最後一個選項是「自定義」。當選擇這一個時,將顯示兩個文本框。MVC驗證RequiredIfTrue不起作用
我的模型:我查看
public class ReportModel
{
public DateType DateType { get; set; }
public List<TypeDTO> DateTypesDTO { get; set; }
[RequiredIfTrue("Custom", ErrorMessage = "Dit veld is verplicht")]
public DateTime? CustomDateFrom { get; set; }
[RequiredIfTrue("Custom", ErrorMessage = "Dit veld is verplicht")]
public DateTime? CustomDateTo { get; set; }
public bool Custom { get; set; }
}
部分:
<div class="control-group">
<label class="control-label">Tijdsinterval</label>
<div class="controls">
@Html.DropDownListFor(m => m.DateType, new SelectList(Model.DateTypesDTO, "DateType", "Translation"), new { id = "timespan", name = "timespan" })
</div>
</div>
<div class="control-group hide" id="custom">
<label class="control-label">Van</label>
<div class="controls controls-margin">
<div class="input-append datetimepicker">
@Html.TextBoxFor(m => m.CustomDateFrom, new { id = "datetimepicker", @class = "add-on", type = "text", data_format = "dd-MM-yyyy hh:mm" })
@Html.ValidationMessageFor(m => m.CustomDateFrom)
@Html.HiddenFor(m => m.Custom);
</div>
</div>
<label class="control-label">Tot</label>
<div class="controls controls-margin">
<div class="input-append datetimepicker">
@Html.TextBoxFor(m => m.CustomDateTo, new { id = "datetimepicker", @class = "add-on", type = "text", data_format = "dd-MM-yyyy hh:mm" })
@Html.ValidationMessageFor(m => m.CustomDateTo)
</div>
</div>
</div>
<script>
$(function() {
$('#partial-view').on('change', '#timespan', function() {
if ($(this).val() == 'Custom') {
$('#custom').show();
} else {
$('#custom').hide();
}
});
});
</script>
的問題是,在控制器if (ModelState.IsValid)
始終是真實的,即使兩個文本框爲空。我究竟做錯了什麼?
你在哪裏設置「自定義」爲真? – Dave
我不這樣做了。 我在onchange函數中首先在JQuery中做了它,但後來我得到一個'Model' = null的異常。 我不知道該在哪裏做。 – Jeffrey
'if($(this).val()=='Custom'){$('#custom')。show(); @ Model.Custom = true; }' 'else {$('#custom')。hide(); @ Model.Custom = false; }' – Jeffrey