在我的项目中使用了ASP.NET MVC 5.我已经使用System.ComponentModel.DataAnnotations
进行验证。
我希望当我没有为必填字段输入值时,请阻止继续我的操作。
但这种期望并不能令人满意。
我该如何解决这个问题?
@model Jahan.Blog.ViewModel.ArticleViewModel
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Article</h4>
<hr />
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.UserId)
@*There are some codes*@
<div class="form-group">
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
</div>
@*There are some codes*@
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
视图模型:
[ModelBinder(typeof(ArticleViewModelBinder))]
public class ArticleViewModel : IArticleViewModel
{
public ArticleViewModel()
{
}
public virtual int Id { get; set; }
[Required]
[StringLength(256)]
public virtual string Title { get; set; }
}
控制器:
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Prefix = "")]ArticleViewModel articleViewModel, List<int> availableTags)
{
if (ModelState.IsValid)
{
// There are some codes.
}
return View(articleViewModel);
}
答案 0 :(得分:0)
打开 web.config ,在ClientValidationEnabled
中找到appSettings
,然后检查它是否设置为true:
<add key="ClientValidationEnabled" value="true" />
答案 1 :(得分:0)
根据Fiskeboss的评论,jquery.validate.unobtrusive.js
库已添加。然后才能正常使用。