在ASP.NET MVC 3中,验证通常放在以下几个位置:
IValidatableObject
接口。ModelState.IsValid
属性检查验证结果。Html.ValidationMessageFor
或Html.ValidationSummary
方法。例如,在模型类中使用数据注解定义验证规则:
public class User
{
[Required]
[StringLength(50)]
public string Name { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
}
在控制器中进行验证:
public ActionResult Create(User user)
{
if (ModelState.IsValid)
{
// 保存数据
return RedirectToAction("Index");
}
return View(user);
}
在视图中显示验证错误信息:
@Html.ValidationSummary(true)
<div>
@Html.LabelFor(model => model.Name)
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div>
@Html.LabelFor(model => model.Email)
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
推荐的腾讯云相关产品:
产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云