【问题标题】:How to validate the HTML controls with data annotations in MVC?如何在 MVC 中使用数据注释验证 HTML 控件?
【发布时间】:2019-09-07 12:52:10
【问题描述】:

在 .Net MVC 中。我有一个 html 控件。为了将它与模型属性绑定,我使用了 name 属性。我们如何将模型类属性中提供的验证(使用数据注释)获取到 html 控件中?

在 Cshtml 中

@using (Html.BeginForm("ClaimWarranty", "WarrentyClaim", FormMethod.Post, new{ enctype = "multipart/form-data" }))
            {
        <div class="form-group row">
         <label for="" class="col-md-2 col-form-label input-label">Email Address:</label>

        <div class="col-md-8">
        <input type="text" name="Emailaddress" class="form-control input-style" placeholder="example@company.com">
         </div>
                                            </div>
        <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Create" onclick="ValidateFileSize()" class="btn btn-default" />

                    </div>
                </div>
        }

    //The model class is below;
     public class ClaimWarranty
        {
     [Required(ErrorMessage = "Email ID is Required")]
            [DataType(DataType.EmailAddress)]
            [MaxLength(50)]
            [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Incorrect Email Format")]
            public string Emailaddress { get; set; }
    }

我正在使用 name 属性将文本框绑定到模型属性。

<input type="text" name="Emailaddress" class="form-control input-style" placeholder="example@company.com"> 

如何在不使用 jquery 验证或 razor 代码的情况下获得模型类中提供的 html 控件中的验证(使用数据注释)(使用数据注释)?

【问题讨论】:

  • 在你的&lt;input&gt;之后添加@Html.ValidationMessageFor(model =&gt;model.Emailaddress , "", new { @class = "text-danger" })
  • 感谢@Nijin Kooderi,上面的评论效果很好
  • 不客气

标签: asp.net-mvc


【解决方案1】:

在视图中

@model Demo.Models.Student
  
@using (Html.BeginForm("SaveStudent", "Student", FormMethod.Post, new { enctype = "multipart/form-data" }))   
{         
<div class="form-group">  
   @Html.LabelFor(model =>model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
   <div class="col-md-10">  
   @Html.EditorFor(model =>model.Name, new { htmlAttributes = new { @class = "form-control" } })  
   @Html.ValidationMessageFor(model =>model.Name, "", new { @class = "text-danger" })  
   </div>  
</div> 

    <div class="form-group">  
        <div class="col-md-offset-2 col-md-10">  
            <input type="submit" value="Create" class="btnbtn-primary" />  
        </div>  
    </div>  

}

在模型中

public class Student
{
  [Required(ErrorMessage = "Please enter name"), MaxLength(30)]   
  public string Name { get; set; }
}

默认情况下,ASP.Net MVC 框架在模型绑定期间执行验证逻辑。在Controller端,我们需要检查

 if (ModelState.IsValid)  
  {  
  }

或者我们也可以勾选个人验证,如下图:

if (ModelState.IsValidField("LastName") == false) 

【讨论】:

  • 是的,如果你解释一下你的代码会是一个更好的答案
【解决方案2】:
if(!ModelState.IsValid) 
{
   // you can get the error information from model state, convert it into list
   var validationErrors = ModelState.Values.Where(E => E.Errors.Count > 0)
                                    .SelectMany(E => E.Errors)
                                    .Select(E => E.ErrorMessage)
                                    .ToList();
   // now you have got the list of errors, you will need to pass it to view
   // you can use view model, viewbag etc
   ViewBag.ErrorList = validationErrors;
   return View();
}
else 
{
     // perform your business operation, save the data to database
     return View();
}

在查看页面上 -

您必须添加检查验证错误列表

if(ViewBag.ErrorList != null) 
{ 
    foreach(var errorMessage in ViewBag.ErrorList) 
    {
       // here you can display the error message and format in html
    }
}


Way you can display error on view page
1. @Html.ValidationSummary() - It will display summary of the validation errors
2. @Html.ValidationMessageFor(x => x.Emailaddress) - It will display error message 
   for specific property
3. you have to manually retrieve the error information from model state and then store it in list and pass to the view page.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    • 1970-01-01
    相关资源
    最近更新 更多