MVC不验证空字符串 [英] MVC not validate empty string
问题描述
我有一个剃刀文件,其中定义了带有字符串文本框的html表单:
I have razor file where I define html form with text box for string:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Product</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
问题是,我希望此字段(model.name)不能为空,但是在我向模型添加空字符串时,剃刀验证允许字符串为空,这会导致错误. 关于如何简单地验证此字符串不再为空的任何建议?
The problem is, that I want this field (model.name) not to be nullable, but razor validation allows string to be empty, when I add empty string to model it gives error. Any suggestions how to validate simply this string not to be empty anymore?
推荐答案
您可能需要设置DataAnnotation属性
You probably need to set the DataAnnotation attribute
[Required(AllowEmptyStrings = false)]
[Required(AllowEmptyStrings = false)]
您要在其中应用验证的属性顶部的
.
在这里看这个问题
在ASP.NET MVC中 RequiredAttribute,AllowEmptyString = true 3项有效的验证
on top of your property where you want to apply the validation.
Look at this question here
RequiredAttribute with AllowEmptyString=true in ASP.NET MVC 3 unobtrusive validation
类似的问题,或多或少都在这里.
如何将具有空值的文本框转换为空字符串
Similar problem, more or less here.
How to convert TextBoxes with null values to empty strings
希望您能够解决您的问题
Hopefully, you'll be able to solve your problem
这篇关于MVC不验证空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!