在视图模型中更改模型状态(添加自定义验证)
Posted
技术标签:
【中文标题】在视图模型中更改模型状态(添加自定义验证)【英文标题】:Change ModelState In viewmodel(Add Custom Validation) 【发布时间】:2016-11-18 05:23:40 【问题描述】:我是 Web 编程新手,我不得不使用 Jquery 数据时间插件。我在数据时间转换中遇到了很多问题,所以我做了一个简单但奇怪而冗长的逻辑来处理它。 而不是创建 One DateTime 属性。我做了两个,一个是字符串,另一个是 ViewModel 中可以为空的日期时间
注意:所有这些代码都是用 ViewModel 编写的
public DateTime? InitialStartDate
get
return istartDate;
set
istartDate = value;
public string IStartDateString
get
if (istartDate == null)
return "";
else
return istartDate.Value.ToString("MM/dd/yyyy");
set
if (string.IsNullOrEmpty(value))
istartDate = null;
else
DateTime TempDate=DateTime.Min;
if(DateTime.TryParseExact(value, "MM/dd/yyyy", CultureInfo.InvariantCulture, out TempDate)
InitialStartDate=TempDate;
else
InitialStartDate=null;
ErrorMessage="Can not convert date";
请告诉我如何很好地处理它。
其次
例如,这个逻辑很好,然后我想添加 ModelState 错误。例如
if(DateTime.TryParseExact(value, "MM/dd/yyyy", CultureInfo.InvariantCulture, out TempDate)
InitialStartDate=TempDate;
else
InitialStartDate=null;
ModelState.AddError('Date is not right ');
有没有这样的。请帮助并非常感谢您阅读我所有的问题:)
例如我这样解析它
InitialStartDate= DateTime.ParseExact(value, "MM/dd/yyyy", CultureInfo.InvariantCulture);
值是 201 年 1 月 1 日 它会抛出异常。我不希望它抛出异常但添加验证错误,所以稍后在控制器中检查 ModelState.IsValid 它返回 false,我可以在视图中显示它。
@html.LabelFor(model => model.InitialStartDate, htmlAttributes: new @class = "control-label col-offset-2" )
@Html.TextBoxFor(model => model.IStartDateString, new @id = "initialstartdate", value = Model.IStartDateString, @class = "form-control", tabindex = "34" )
@Html.ValidationMessageFor(model => model.InitialStartDate, "", new @class = "text-danger" )
我正在从视图中设置它的值。
在我的模型中包含所有其他属性。我有这个
[DataType(DataType.Date)]
public DateTime? StartTime get; set;
【问题讨论】:
您想解决什么样的问题?在带有 jquery datetime 插件的 MVC 中,我经常使用带有Html.EditorFor
模型绑定的 jQuery datepicker,将模型发送到控制器并在给定无效日期时间格式时执行 ModelState.AddModelError("message")
。请尽可能向我解释详细的预期结果。
@TetsuyaYamamoto 在问题末尾添加了更多文字。
value
变量从哪里获取数据?如果您有模型类,请显示它。我发现您想在无效的日期时间格式上使 ModelState
无效并在您的视图中显示错误消息。
@TetsuyaYamamoto 添加了更多文本。请看一下
【参考方案1】:
试试这个
$(function()
$("#datepicker").datepicker(
changeMonth: true,
changeYear: true,
yearRange: '2011:2037',
dateFormat: 'dd/mm/yy',
minDate: 0,
defaultDate: null
).on('change', function()
$(this).valid(); // triggers the validation test
// '$(this)' refers to '$("#datepicker")'
);
);
希望对你有帮助。
【讨论】:
【参考方案2】:使用 try-catch 块并将ModelState.AddModelError
添加到您的代码中:
查看
<script type="text/javascript">
$(document).ready(function()
$("#initialstartdate").datepicker(
changeMonth: true,
changeYear: true,
dateFormat: 'MM/dd/yyyy',
minDate: 0,
defaultDate: null
// see jQuery datepicker docs for more attributes
).change(function()
$(this).valid(); // validation test
);
);
</script>
<!-- EditorFor used to include datetime as is -->
@Html.EditorFor(model => model.IStartDateString, new @id = "initialstartdate", value = Model.IStartDateString, @class = "form-control", tabindex = "34" );
控制器
try
if(DateTime.TryParseExact(value, "MM/dd/yyyy", CultureInfo.InvariantCulture, out TempDate)
InitialStartDate=TempDate;
else
InitialStartDate = null;
ModelState.AddModelError("Date is not right");
catch (ArgumentException e)
ModelState.AddModelError("Date is not right");
ModelState.AddModelError
将使ModelState
无效,结果IsValid
属性在返回视图时变为false
。
这可能与您当前的需求相去甚远,因此欢迎提出任何建议。
【讨论】:
以上是关于在视图模型中更改模型状态(添加自定义验证)的主要内容,如果未能解决你的问题,请参考以下文章
ASP .NET Core 5 Razor Pages:如何正确使用局部视图并验证其模型状态?
带有来自模型的自定义验证消息的 Django 1.5 基于类的视图