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

4
以下是使用for循环生成HTML表并绑定文本框和下拉列表的代码,同时使用jQuery无侵入式库验证文本框和下拉列表。虽然一切都正常工作,但我希望以不同的方式自定义验证。在我的情况下,验证消息正在显示,但我希望验证消息不会显示,而是当用户将鼠标光标放在红色边框文本框或下拉列表上时,验证消息将显示为工具提示。如何将验证消息附加到文本框和下拉列表的title属性上?以下是完整的代码,请查看并提出建议或更正样例,如何修改现有代码以实现所需功能。
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; }
    }
}

Controllers

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>
}

屏幕截图

输入图片描述


这篇文章介绍了如何使用qTip工具提示在ASP.NET MVC中显示客户端和服务器端验证结果,可能会对你有所帮助。 - Umesh Sehta
3个回答

8

不要使用 [Required],尝试使用 [Required (ErrorMessage = "请添加内容!")]


如果我这样做,那么会显示“请添加内容”的消息,但我不想显示验证消息,而是想将验证消息附加到HTML控件上。假设第二行中的名字文本框为空。因此,当验证触发时,第二行中的名字文本框将具有红色边框,当用户将鼠标放在该文本框上时,将在工具提示中显示验证消息。 工具提示意味着标题属性。 - Mou
@Mou,你可以在其中放置HTML标记,并且可以根据需要进行样式设置。将RequiredAttribute扩展会更加清晰,而不是在每个属性上都这样做。 - NikolaiDante

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>

上面输入字段中给出的id作为DestinationPhoneNmber虽然不是必需的,但如果我们在输入字段中没有分配任何id,则默认情况下它会将模态属性名称作为其id。

我使用Bootstrap类隐藏了由@Html.ValidationMessageFor(model => model.xyz)生成的HTML,但是如果您不使用Bootstrap,则必须使用CSS来隐藏它。 - Anil Panwar
@Html.ValidationMessageFor(model => model.xyz) 会生成 <span class="field-validation-error" data-valmsg-for="" data-valmsg-replace="true">验证信息</span>。 - Anil Panwar
它永远不会为空,数据注释会自动添加,data-valmsg-for="Model property name by default same as the name of modal property"。 - Anil Panwar
我把你的脚本放在 document.ready 中,但仍然无法工作。 - Mou
你的脚本在那个编辑器中没有运行,请尝试将警告放在for循环内以进行调试。 - Anil Panwar
显示剩余6条评论

0

使用 @Html.ValidationMessageFor(m => m.Students[i].ID, "", new { @style = "text-decoration: underline; 和其他样式...", @class = "someclass" })

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


我想知道如何在正确的控件中添加错误消息到标题属性? - Mou

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接