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

时间:2016-01-15 10:45:46

标签: c# jquery asp.net-mvc validation

下面是我在for循环中生成html表并绑定textbox&的代码。落下。还使用jquery unobtrusive库来验证textbox&下拉列表。

所有工作,但我想自定义验证位不同的方式。在我的案例验证消息显示,但我希望验证消息不会显示而不是当用户将鼠标光标放在红色边框文本框或红色边框下拉列表然后验证消息将显示为工具提示。

如何将验证消息附加到文本框和下拉列表的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; }
    }
}

控制器

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

屏幕截图

enter image description here

3 个答案:

答案 0 :(得分:3)

而不是[Required]尝试[Required (ErrorMessage = "Please add something!" )]

答案 1 :(得分:2)

更新代码:

查看:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'caffeineCacheManager' defined in com.myapp.spring.config.CacheConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cache.jcache.JCacheCacheManager]: Factory method 'getSpringCacheManager' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5266)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5554)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:677)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1912)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cache.jcache.JCacheCacheManager]: Factory method 'getSpringCacheManager' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 34 more
Caused by: java.lang.NullPointerException
    at com.github.benmanes.caffeine.jcache.CacheProxy.<init>(CacheProxy.java:109)
    at com.github.benmanes.caffeine.jcache.CacheFactory$Builder.newCacheProxy(CacheFactory.java:160)
    at com.github.benmanes.caffeine.jcache.CacheFactory$Builder.build(CacheFactory.java:145)
    at com.github.benmanes.caffeine.jcache.CacheFactory.createCache(CacheFactory.java:82)
    at com.github.benmanes.caffeine.jcache.CacheManagerImpl.lambda$createCache$0(CacheManagerImpl.java:98)
    at com.github.benmanes.caffeine.jcache.CacheManagerImpl$$Lambda$23/388708304.apply(Unknown Source)
    at java.util.concurrent.ConcurrentHashMap.compute(ConcurrentHashMap.java:1853)
    at com.github.benmanes.caffeine.jcache.CacheManagerImpl.createCache(CacheManagerImpl.java:94)
    at com.myapp.spring.config.CacheConfig.getSpringCacheManager(CacheConfig.java:55)
    at com.myapp.spring.config.CacheConfig$$EnhancerBySpringCGLIB$$4f46e611.CGLIB$getSpringCacheManager$1(<generated>)
    at com.myapp.spring.config.CacheConfig$$EnhancerBySpringCGLIB$$4f46e611$$FastClassBySpringCGLIB$$b70e5f67.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:355)
    at com.myapp.spring.config.CacheConfig$$EnhancerBySpringCGLIB$$4f46e611.getSpringCacheManager(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 35 more

模态:

@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);
              });

<强> Genrates

  @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)

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

答案 2 :(得分:0)

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

然后,您可以根据类名

自定义CSS文件中的样式