我正在使用Asp.net核心构建一个Web应用程序。我正在使用内置核心验证方法。我有一个表单,我想使用数据注释应用客户端验证。我的模型如下所示:
[Display(Name= "Address")]
[Required]
[StringLength(80, MinimumLength = 5)]
public string Address { get; set; }
[Display(Name = "When it is needed")]
[Required]
[DataType(DataType.Date)]
public DateTime TakeDownDate { get; set; }
[Display(Name = "Exact time")]
[Required]
[DataType(DataType.Time)]
public TimeSpan ExactTimeToTakeDown { get; set; }
[Display(Name = "Content of container")]
public ContainerContentEnum? Content { get; set; }
[Display(Name = "When to take up")]
[DataType(DataType.Date)]
public DateTime? TakeUpDate { get; set; }
[Display(Name= "Other comment")]
[StringLength(250)]
public string Other { get; set; }
[Display(Name = "Multiple round")]
public bool MaybeMoreRound { get; set; }
让我们看一下TakeUpDate属性。它是可空的,所以我允许用户不在字段中输入任何内容来提交表单。提交表单后,它将由相应的控制器方法处理:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult SaveNewClaim(NewClaimViewModel newClaim)
{
if (ModelState.IsValid)
{
_claimsRepository.Insert(_newClaimViewModelToClaimConverterService.Convert(newClaim));
return CreateJsonResult(true, "Az igény sikeresen lementésre került");
}
return CreateJsonResult(false, GetErrorMessages());
}
private JsonResult CreateJsonResult(bool isSuccess, string responseMessage)
{
return Json(new
{
success = isSuccess,
responseText = responseMessage
}
);
}
private string GetErrorMessages()
{
return string.Join(";\n", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
}
至于视图,.cshtml文件如下所示:
@using App.ViewModels.ClaimViewModels.ClaimModels
@model App.ViewModels.ClaimViewModels.ClaimModels.NewClaimViewModel
<div id="calendarModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true"></span> <span class="sr-only">close</span></button>
<h3><b>Új igény felvétele</b></h3>
</div>
<div id="modalBody" class="modal-body">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<form asp-action="SaveNewClaim" id="EventForm" class="well">
<input type="hidden" id="eventID" class="form-control">
<div class="form-group">
<label asp-for="Address" class=""></label>
<div class="">
<input asp-for="Address" class="form-control">
<span asp-validation-for="Address" class="text-danger"> </span>
</div>
</div>
<div class="form-group">
<label asp-for="TakeDownDate" class=""></label>
<div class="">
<input asp-for="TakeDownDate" class="form-control" />
<span asp-validation-for="TakeDownDate" class="text-danger"> </span>
</div>
</div>
<div class="form-group">
<label asp-for="ExactTimeToTakeDown" class=""></label>
<div class="">
<input asp-for="ExactTimeToTakeDown" class="form-control" />
<span asp-validation-for="ExactTimeToTakeDown" class="text-danger"> </span>
</div>
</div>
<div class="form-group">
<label asp-for="Content" class=""></label>
<div class="">
<select asp-for="Content" asp-items="@Html.GetEnumSelectList<MokaKukaMap.Domain.Model.ContainerContentEnum>()" class="form-control">
<option selected="selected" value="">Kérem válassz</option>
</select>
<span asp-validation-for="Content" class="text-danger"> </span>
</div>
</div>
<div class="form-group">
<label asp-for="TakeUpDate" class=""></label>
<div class="">
<input asp-for="TakeUpDate" class="form-control" />
<span asp-validation-for="TakeUpDate" class="text-danger"> </span>
</div>
</div>
<div class="form-group">
<label asp-for="Other" class=""></label>
<div class="">
<input asp-for="Other" class="form-control" />
<span asp-validation-for="Other" class="text-danger"> </span>
</div>
</div>
<div class="form-group">
<label asp-for="MaybeMoreRound" class=""></label>
<div class="">
<input asp-for="MaybeMoreRound" type="checkbox" class="form-control" />
<span asp-validation-for="MaybeMoreRound" class="text-danger"> </span>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnPopupCancel" data-dismiss="modal" class="btn">Vissza</button>
<button type="button" id="btnPopupSave" class="btn btn-primary">Igény mentése</button>
</div>
</div>
</div>
</div>
最后但并非最不重要的是我在提交按钮上的ajax帖子(点击事件):
$('#btnPopupSave').click(function () {
var dataRow = {
Address: $('#Address').val(),
TakeDownDate: $('#TakeDownDate').val(),
ExactTimeToTakeDown: $('#ExactTimeToTakeDown').val(),
Content: $('#Content').val(),
TakeUpDate: $('#TakeUpDate').val(),
Other: $('#Other').val(),
MaybeMoreRound: $('#MaybeMoreRound').val()
}
console.log('Submitting form...');
$.ajax({
type: 'POST',
url: 'SaveNewClaim',
data: dataRow,
headers:
{
"RequestVerificationToken": '@GetAntiXsrfRequestToken()'
},
dataType: 'json',
success: function (response) {
if (response.success) {
$('#calendarModal').modal('hide');
$('#calendar').fullCalendar('refetchEvents');
alert(response.responseText);
}
else {
alert(response.responseText);
}
},
error: function(xMlHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest.responseText);
console.log(textStatus);
console.log(errorThrown);
}
});
});
尽管我将TakeUpDate设置为可空,但我的模型仍然无效,我收到以下错误消息: 价值&#39;何时采取&#39;是无效的。
老实说,我在stackoverflow和其他论坛中检查了每个相关的Q / As,并且所有人都说这是设置字段可空的正确方法。
如果您需要更多代码,我会立即将其添加到此问题中......
答案 0 :(得分:2)
根本问题在于您将空字符串传递回控制器。
您需要捕获该空字符串并在模型绑定发生之前将其转换为null,或者您需要解决已知的错误问题。并且处理此时你的验证总是会失败的事实。
您可以更改Ajax POST以显式发送空值。
另外(也可能是我做的)只是在理智中检查您在控制器中的日期。如果它是一个空字符串,则将其从ModelState中删除,这样它就不会被标记为无效(因为你已经知道它是什么以及为什么)。 ModelState仍然会正常验证其他字段。
如下所示:
public IActionResult SaveNewClaim(NewClaimViewModel newClaim)
{
if (newClaim.TakeUpDate == "")
{
ModelState.Remove("TakeUpDate");
}
if (ModelState.IsValid)
{
newClaim.TakeUpDate = null;
_claimsRepository.Insert(_newClaimViewModelToClaimConverterService.Convert(newClaim));
return CreateJsonResult(true, "Az igény sikeresen lementésre került");
}
return CreateJsonResult(false, GetErrorMessages());
}