我有剃刀文件,我用字符串的文本框定义html表单:
@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)不可为空,但剃刀验证允许字符串为空,当我将空字符串添加到模型时它会给出错误。任何建议如何验证这个字符串不再是空的?
您可能需要设置DataAnnotation属性
[必需(AllowEmptyStrings = false)]
在您想要应用验证的属性顶部。 看看这个问题 RequiredAttribute with AllowEmptyString=true in ASP.NET MVC 3 unobtrusive validation
类似的问题,或多或少在这里。 How to convert TextBoxes with null values to empty strings
希望你能够解决你的问题
你的viewmodel是什么样的?
您可以在viewmodel中的DataAnnotation
属性中添加Name
属性:
public class MyViewModel
{
[Required(ErrorMessage="This field can not be empty.")]
public string Name { get; set; }
}
然后,在您的控制器中,您可以检查发布的模型是否有效。
public ActionResult MyAction(ViewModel model)
{
if (ModelState.IsValid)
{
//ok
}
else
{
//not ok
}
}
这对我有用: 使用以下行不接受空字符串 [必需(AllowEmptyStrings = false)] 那个不允许空白的人 [RegularExpression(@“。\ S +。”,ErrorMessage =“不允许空格”)]