ASP.Net MVC:如何自定义验证消息显示

Posted

技术标签:

【中文标题】ASP.Net MVC:如何自定义验证消息显示【英文标题】:ASP.Net MVC: How to customize validation message showing 【发布时间】:2016-04-20 22:40:47 【问题描述】:

下面是我在 for 循环中生成 html 表并绑定文本框和下拉列表的代码。还使用 jquery unobtrusive library 来验证文本框和下拉列表。

一切正常,但我想以不同的方式自定义验证。在我的情况下,验证消息正在显示,但我希望验证消息不会显示,而是当用户将鼠标光标放在红色边框文本框或红色边框下拉菜单上时,验证消息将显示为工具提示。

如何将验证消息附加到文本框和下拉列表的标题属性?

这是我的完整代码。请查看并提供建议或修正示例,例如在我现有的代码中添加或更改什么以实现我想要的。

模型和视图模型

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace RemoveValidateMessage.Models

    public class MainViewModel
    
        public List<Student> Students  get; set; 
        public int SelectedState = 0;
        public int SelectedCity = 0;
    

    public class Student
    
        [Required]
        public int ID  get; set; 

        [Required]
        public string Name  get; set; 

        [Required]
        public int StateID  get; set; 

        [Required]
        public int CityID  get; set; 
        public List<States> States  get; set; 
        public List<Cities> Cities  get; set; 
    

    public class States
    
        public int ID  get; set; 
        public string Name  get; set; 
    

    public class Cities
    
        public int ID  get; set; 
        public string Name  get; set; 
    

控制器

using RemoveValidateMessage.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RemoveValidateMessage.Controllers

    public class HomeController : Controller
    
        public ActionResult Index()
        
            MainViewModel oVm = new MainViewModel()
            
                Students = new List<Student>() 
                    new Student
                    
                        ID=1,
                        Name="JoyDev",
                        StateID=1,
                        CityID=1,
                        States=new List<States>()
                        
                            new States
                            
                                ID=1,
                                Name="WestBengal",
                            ,
                            new States
                            
                                ID=2,
                                Name="Bihar",
                            ,
                            new States
                            
                                ID=3,
                                Name="Orrisa",
                            

                        ,
                        Cities=new List<Cities>()
                        
                            new Cities
                            
                                ID=1,
                                Name="Alipur"
                            ,
                            new Cities
                            
                                ID=2,
                                Name="Asansol"
                            ,
                            new Cities
                            
                                ID=3,
                                Name="Andul"
                            

                        
                    ,

//***********
                    new Student
                    
                        ID=1,
                        Name="Mukti",
                        StateID=2,
                        CityID=1,
                        States=new List<States>()
                        
                            new States
                            
                                ID=1,
                                Name="WestBengal",
                            ,
                            new States
                            
                                ID=2,
                                Name="Bihar",
                            ,
                            new States
                            
                                ID=3,
                                Name="Orrisa",
                            

                        ,
                        Cities=new List<Cities>()
                        
                            new Cities
                            
                                ID=1,
                                Name="Janpur"
                            ,
                            new Cities
                            
                                ID=2,
                                Name="Madhubani"
                            ,
                            new Cities
                            
                                ID=3,
                                Name="Kanti"
                            

                        
                    ,
//***********
                    new Student
                    
                        ID=1,
                        Name="Somnath",
                        StateID=3,
                        CityID=2,
                        States=new List<States>()
                        
                            new States
                            
                                ID=1,
                                Name="WestBengal",
                            ,
                            new States
                            
                                ID=2,
                                Name="Bihar",
                            ,
                            new States
                            
                                ID=3,
                                Name="Orrisa",
                            

                        ,
                        Cities=new List<Cities>()
                        
                            new Cities
                            
                                ID=1,
                                Name="Chandapur"
                            ,
                            new Cities
                            
                                ID=2,
                                Name="Dhankauda"
                            ,
                            new Cities
                            
                                ID=3,
                                Name="Konarak"
                            

                        
                    


                

            ;


            return View(oVm);
        

        [HttpPost]
        public ActionResult Index(MainViewModel model)
        
            //if (ModelState.IsValid)
            //
            //    return View(model);
            //
            for (int i = 0; i < model.Students.Count;i++ )
            
                model.Students[i].States = new List<States>()
                        
                            new States
                            
                                ID=1,
                                Name="WestBengal",
                            ,
                            new States
                            
                                ID=2,
                                Name="Bihar",
                            ,
                            new States
                            
                                ID=3,
                                Name="Orrisa",
                            

                        ;
                model.Students[i].Cities = new List<Cities>()
                        
                            new Cities
                            
                                ID=1,
                                Name="Chandapur"
                            ,
                            new Cities
                            
                                ID=2,
                                Name="Dhankauda"
                            ,
                            new Cities
                            
                                ID=3,
                                Name="Konarak"
                            

                        ;
            
            return View(model);
        
        public ActionResult Test()
        
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            ViewBag.Time = DateTime.Now.ToString();
            return View();
        


        public ActionResult About()
        
            ViewBag.Message = "Your app description page.";

            return View();
        

        public ActionResult Contact()
        
            ViewBag.Message = "Your contact page.";

            return View();
        
    

查看代码

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

@model RemoveValidateMessage.Models.MainViewModel
@
    ViewBag.Title = "Home Page";


@using (Html.BeginForm("Index", "Home",FormMethod.Post))
 
<div>
    <table>
        <tr>
            <td>ID</td>
            <td>Name</td>
            <td>State</td>
            <td>City</td>
        </tr>
        @for (int i = 0; i < Model.Students.Count; i++)
        
            <tr>
                <td>
                    @*<input type="text" value="@Model.Students[i].ID" />*@
                @Html.EditorFor(m=>m.Students[i].ID)
                @Html.ValidationMessageFor(m => m.Students[i].ID)
                </td>

                <td>
                @*<input type="text" value="@Model.Students[i].Name" />*@
                    @Html.EditorFor(m => m.Students[i].Name)
                    @Html.ValidationMessageFor(m => m.Students[i].Name)
                </td>
                <td>
                    @Html.DropDownListFor(m => m.Students[i].StateID, new SelectList(Model.Students[i].States, "ID", "Name", Model.Students[i].StateID), "-- Select States--", new  @class = "edit-mode" )
                    @Html.ValidationMessageFor(m => m.Students[i].StateID)
                </td>
                <td>
                   @Html.DropDownListFor(m => m.Students[i].CityID, new SelectList(Model.Students[i].Cities, "ID", "Name", Model.Students[i].CityID), "--Select States--", new  @class = "edit-model" )
                    @Html.ValidationMessageFor(m => m.Students[i].CityID)
                </td>
            </tr>
        
    </table>
</div>
 <p><input type="submit" value="Submit" /></p>

屏幕截图

【问题讨论】:

这可能对nickstips.wordpress.com/2011/08/18/…有帮助 【参考方案1】:

代替[Required] 试试[Required (ErrorMessage = "Please add something!" )]

【讨论】:

如果我这样做了,那么这条消息将显示“请添加一些东西”,但我不想显示验证消息,而是想用 html 控件附加验证消息。假设第 2 行的名字文本框为空。所以我当验证将触发时,第二行中的名字文本框将有红色边框,当用户将鼠标放在该文本框上时,验证消息将显示在工具提示中。 tooltip 表示标题属性。 @Mou 你可以把 html 标记进去,你可以按照你想要的方式设置样式。 extend RequiredAttribute 比在每个属性上都这样做更干净。【参考方案2】:

更新代码:

查看:

@model HelloWorldMvcApp.MainViewModel
@
    Layout = null;


<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>


<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


@using (Html.BeginForm("Index", "Home", FormMethod.Post))

    <div>
        <table>
            <tr>
                <td>ID</td>
                <td>Name</td>
                <td>State</td>
                <td>City</td>
            </tr>
            @for (int i = 0; i < Model.Students.Count; i++)
            
                <tr>
                    <td>
                        @*<input type="text" value="@Model.Students[i].ID" />*@
                        @Html.EditorFor(m => m.Students[i].ID)
                        @Html.ValidationMessageFor(m => m.Students[i].ID)
                    </td>

                    <td>
                        @*<input type="text" value="@Model.Students[i].Name" />*@
                        @Html.EditorFor(m => m.Students[i].Name)
                        @Html.ValidationMessageFor(m => m.Students[i].Name)
                    </td>
                    <td>
                        @Html.DropDownListFor(m => m.Students[i].StateID, new SelectList(Model.Students[i].States, "ID", "Name", Model.Students[i].StateID), "-- Select States--", new  @class = "edit-mode" )
                        @Html.ValidationMessageFor(m => m.Students[i].StateID)
                    </td>
                    <td>
                        @Html.DropDownListFor(m => m.Students[i].CityID, new SelectList(Model.Students[i].Cities, "ID", "Name", Model.Students[i].CityID), "--Select States--", new  @class = "edit-model" )
                        @Html.ValidationMessageFor(m => m.Students[i].CityID)
                    </td>
                </tr>
            
        </table>
    </div>
    <p><input type="submit" value="Submit" /></p>



<script>
    $(document).ready(function () 
        $("form").on("submit",function()
            if ($("span[class='field-validation-error']").length != 0)
                $("span[class='field-validation-error']").each(function () 
                    $(this).addClass("hidden");//Add class hidden to hide  @@Html.ValidationMessageFor(model => model.xyz) if using bootstrap , else use css
                    var inputID = $(this).prev("input").attr("id");//get the id of the input field for which this validation prompted
                    $(this).prev("input select").css("border", "1px solid red");
                  //  $(this).prev("select").css("border", "1px solid red");
                    var validationMessage = $(this).text();//Get validation message for input filed which is prompted
                    $("#" + inputID).tooltip( 'trigger': 'hover', 'title': validationMessage );//Trigger the tooltip now, if using bootstrap.
                );
        );
    );
</script>

模态:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace HelloWorldMvcApp

    public class MainViewModel
    
        public List<Student> Students  get; set; 
        public int SelectedState = 0;
        public int SelectedCity = 0;
    

    public class Student
    
        [Required]
        public int ID  get; set; 

        [Required]
        public string Name  get; set; 

        [Required]
        public int StateID  get; set; 

        [Required]
        public int CityID  get; set; 
        public List<States> States  get; set; 
        public List<Cities> Cities  get; set; 
    

    public class States
    
        public int ID  get; set; 
        public string Name  get; set; 
    

    public class Cities
    
        public int ID  get; set; 
        public string Name  get; set; 
    

控制器:

using HelloWorldMvcApp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HelloWorldMvcApp

    public class HomeController : Controller
    
            public ActionResult Index()
            
            MainViewModel oVm = new MainViewModel()
            
                Students = new List<Student>() 
                    new Student
                    
                        ID=1,
                        Name="JoyDev",
                        StateID=1,
                        CityID=1,
                        States=new List<States>()
                        
                            new States
                            
                                ID=1,
                                Name="WestBengal",
                            ,
                            new States
                            
                                ID=2,
                                Name="Bihar",
                            ,
                            new States
                            
                                ID=3,
                                Name="Orrisa",
                            

                        ,
                        Cities=new List<Cities>()
                        
                            new Cities
                            
                                ID=1,
                                Name="Alipur"
                            ,
                            new Cities
                            
                                ID=2,
                                Name="Asansol"
                            ,
                            new Cities
                            
                                ID=3,
                                Name="Andul"
                            

                        
                    ,

//***********
                    new Student
                    
                        ID=1,
                        Name="Mukti",
                        StateID=2,
                        CityID=1,
                        States=new List<States>()
                        
                            new States
                            
                                ID=1,
                                Name="WestBengal",
                            ,
                            new States
                            
                                ID=2,
                                Name="Bihar",
                            ,
                            new States
                            
                                ID=3,
                                Name="Orrisa",
                            

                        ,
                        Cities=new List<Cities>()
                        
                            new Cities
                            
                                ID=1,
                                Name="Janpur"
                            ,
                            new Cities
                            
                                ID=2,
                                Name="Madhubani"
                            ,
                            new Cities
                            
                                ID=3,
                                Name="Kanti"
                            

                        
                    ,
//***********
                    new Student
                    
                        ID=1,
                        Name="Somnath",
                        StateID=3,
                        CityID=2,
                        States=new List<States>()
                        
                            new States
                            
                                ID=1,
                                Name="WestBengal",
                            ,
                            new States
                            
                                ID=2,
                                Name="Bihar",
                            ,
                            new States
                            
                                ID=3,
                                Name="Orrisa",
                            

                        ,
                        Cities=new List<Cities>()
                        
                            new Cities
                            
                                ID=1,
                                Name="Chandapur"
                            ,
                            new Cities
                            
                                ID=2,
                                Name="Dhankauda"
                            ,
                            new Cities
                            
                                ID=3,
                                Name="Konarak"
                            

                        
                    


                

            ;


            return View(oVm);
        

    

下面的代码我已经测试过了。

 $("span[class='field-validation-error']").each(function () 

            $(this).addClass("hidden");//Add class hidden to hide  @@Html.ValidationMessageFor(model => model.xyz) if using bootstrap , else use css
            var inputID = $(this).attr("data-valmsg-for");//get the id of the input field for which this validation prompted
            var validationMessage = $(this).html();//Get validation message for input filed which is prompted          
            $("#" + inputID).tooltip( 'trigger': 'hover', 'title': validationMessage );//Trigger the tooltip now, if using bootstrap.

                      //******OR*******

            $("#" + inputID).attr("tooltip",validationMessage);
              );

要理解上面的代码,请看:

  @Html.LabelFor(model => model.DestinationPhoneNmber, new  @class = "control-label" )
                    @Html.TextBoxFor(model => model.DestinationPhoneNmber, new  @class = "form-control", @id = "DestinationPhoneNmber", @placeholder = "+919876543210" )
                    @Html.ValidationMessageFor(model => model.DestinationPhoneNmber)

生成

            <label class="control-label" for="DestinationPhoneNmber">Destination Phone Number*</label>
            <input class="input-validation-error form-control" data-val="true" data-val-required="Please enter the destination phone number!" id="DestinationPhoneNmber" name="DestinationPhoneNmber" placeholder="+919876543210" type="text" value="">
            <span class="field-validation-error" data-valmsg-for="DestinationPhoneNmber" data-valmsg-replace="true">Please enter the destination phone number!</span>

在上述输入字段中作为 DestinationPhoneNmber 给出的 id 虽然不是必需的,因为我们没有在输入字段中分配任何 id,它默认将模态属性名称作为其 id。

【讨论】:

你隐藏了什么$(this).addClass("hidden")这个代码目标不清楚? 我使用 bootstrap 类隐藏了从 @Html.ValidationMessageFor(model => model.xyz) 生成的 html,但是由于您没有使用 bootstrap,因此您必须使用 css 来隐藏它。 @Html.ValidationMessageFor(model => model.xyz) 生成 验证消息 在这里你粘贴 html 代码用于验证消息,其中 data-valmsg-for="" 但在上面的代码中你阅读 var inputID = $(this).attr("data-valmsg-for") data-valmsg-for="" 是空的,那么将存储什么在 inputID 中? $(this) 是当前跨度,因为我们使用的每个跨度都具有类 field-validation-error,并且 data-valmsg-for="" 存储输入字段的 id。如果 @Html.TextBoxFor(model => model.xyz) 是我的输入字段,那么它的 id 默认为 xyz。【参考方案3】:

使用@Html.ValidationMessageFor(m =&gt; m.Students[i].ID, "", new @style = "text-decoration: underline; and some other styles...", @class = "someclass" )

然后你可以根据类名从 CSS 文件中自定义样式

【讨论】:

我想知道如何使用正确的控件将错误消息添加到标题属性?

以上是关于ASP.Net MVC:如何自定义验证消息显示的主要内容,如果未能解决你的问题,请参考以下文章

如何在 ASP.NET MVC 5 中实现自定义身份验证

自定义属性的 ASP.NET MVC 客户端验证

如何在 ASP.NET MVC 3 中自定义不显眼的验证以匹配我的风格?

ASP.Net Core MVC - 自定义验证

如何在 Asp.Net Mvc 3 中显示自定义错误页面?

ASP.NET MVC5 自定义身份验证