如何解决mvc验证错误

时间:2017-01-19 06:40:58

标签: javascript jquery .net asp.net-mvc-4

 public String Name {Get;Set;} 
 Public String LastName {Get;Set;} 
 Public String Age {Get;Set;} 
 [required]
 public Comment{Get;Set;}

        <body>
        <table>
        <tr>
        <td>
        @html.textboxfor(m=>m.name)
        </td>
        <td>
        <input type="submit">Search</input>
        </td>
        <tr>
        </table>
    <table>
    <tr>
    <td>
        @html.textboxfor(m=>m.comment)
    </td>
 <td>
        <input type="submit">Save</input>
        </td>
    </tr>
    </table>
        </body>

单击按钮时模型Valiadtion应用于注释但是当Save Buuton单击验证是数据注释验证时验证适用于coomnt

1 个答案:

答案 0 :(得分:0)

你必须使用Jquery Unobstrusive验证进行即时验证,就像这样;

模型类

public class UserModel
{
   [Required(ErrorMessage ="Name is Mandatory")]
   public string FirstName {get;set;}
   [Required(ErrorMessage ="Last Name Field is Mandatory")] 
   Public string LastName {get;set;} 
   Public string Age {get;set;} 
   [required]
   public Comment{get;set;}
}

在你的CsHtml文件中请包括Thes Libraries

<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

之后更改您的查看代码并添加ValidateMessageFor以显示错误

@Html.TextBoxFor(m=>m.FirstName)
@Html.ValidationMessageFor(m => m.FirstName, null, new { @class = "" })