Adding Hyperlinks to ValidationSummary

放肆的年华 提交于 2019-12-11 05:57:36

问题


I have a long form for my users to fill out. Is there a way to hyperlink the error message in ValidationSummary to the specific text field?


回答1:


The easiest way to do this is with straightforward HTML anchor tags <a>, you can include the HTML in the ErrorMessage property of your validation control which will be displayed in your ValidationSummary control. For examples

<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<asp:Button ID="Button5" runat="server" Text="Submit" />
<br />
<div style="height:800px"></div>
<a name="TextBox1"></a>
Required Field
<asp:TextBox ID="TextBox1" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
    ErrorMessage="Required Field is Required <a href='#TextBox1'>Click Here To Go To</a>" 
    Text="***" 
    ControlToValidate="TextBox1" />

A more elegant approach would be to combine the above approach with jQuery using the scrollTo function and perhaps highlighting the field. You can include this jQuery/Javascript code in the onclick property of the anchor tag.




回答2:


I've implemented this before in the same way @jdmonty had suggested - by adding the anchor tags to each RFV's ErrorMessage attribute. Eventually I found this too tedious so I drummed up some jQuery to do the work for me. This snippet will wrap your validation messages in anchor tags with the href=#targetControl, which of course when clicked scrolls to the target input.

Add this to the $(document).ready(); portion of your script code.

   var validators = Page_Validators;   // returns collection of validators on page

        $(validators).each(function () {
            //get target control and current error validation message from each validator
            var errorMsg = $(this).context.errormessage;
            var targetControl = $(this).context.controltovalidate;
            var errorMsgWithLink = "<a href='#" + targetControl + "'> " + errorMsg + "</a>";

            //update error message with anchor tag
            $(this).context.errormessage = errorMsgWithLink;
        });

You could add some additional jQuery as @jdmonty suggested to smooth the scrolling. You can also use the css pseudo class ':focus' in your style sheet to add styles for 'active' input textboxes, something like input[type=text]:focus{background-color:red;} to really accentuate when they are focused.

P.S. I know this question is old but I just found it today while seeing if anyone had come up with a more elegant solution, so for anyone else in my shoes, here ya go.



来源:https://stackoverflow.com/questions/6778224/adding-hyperlinks-to-validationsummary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!