RequiredFieldValidator places display:inline on the text - asp.net

I have a RequiredFieldValidator with Display="Dynamic" on my ASP.NET WebForm. I have assigned it a class using the CssClass property. I want the error message to be displayed using display: block, so I have placed this on the css class in my style sheet.
Unfortunately, the validator places a display: inline on the element on the web page, effectivaly overriding my style sheet value.
Can I get rid of that?
Edit:
I just realised why this doesn't work. When setting Display="Dynamic" on a validator, it has the effect that it sets style="display: none" on the span tag when rendering. The .net javascript library then switches the inline style of the element between none and inline. That is simply how the dynamic validator works.
So for this to display as a block element, I will need to modify how the client side event validation works. Is it possible to do that?

Using CSS attribute selector and !important I did it. I had to use the "contains" selector to get it working in FF, but now I have tested it in IE10, FF and Chrome and so far it is working. It is really simple.
Here is a sample validator in my aspx page:
<asp:RequiredFieldValidator runat="server" ID="rfvRequired" ErrorMessage="This is required.<br/>This is line 2" ControlToValidate="tbRequired" ValidationGroup="CommonAttributesValidationGroup" SetFocusOnError="True" CssClass="valerror" Display="Dynamic"></asp:RequiredFieldValidator>
Next I have a style for valerror.
span.valerror[style*="inline"]
{
display:block !important;
background-color: Yellow;
border: 1px solid #cccccc;
font-size:.9em;
}
That is it. How it works: when the span changes the style from "display:none" to "display:inline" the attribute selector on the span kicks in and forces it to be a block. You just need to make ONE CSS entry like the one above and make sure you make each validator that class.

An extremely hacky solution I once used (which I'm not proud of, but it worked) was to wrap the RequiredFieldValidator in a <div>, which is a block element; therefore even though your RequiredFieldValidator is inline, it's inside a block div so it'll effectively appear as display:block in most cases.
Told you it was hacky!

Maybe this can help you:
http://caliberwebgroup.blogspot.com/2009/02/overriding-javascript-in-webresourceaxd.html

I have found a solution that works by overriding the .net ValidatorUpdateDisplay() method in JavaScript, and needs to be put before the close body tag.
<script type="text/javascript">
function ValidatorUpdateDisplay(val)
{
if (typeof (val.display) == "string")
{
if (val.display == "None")
{
return;
}
if (val.display == "Dynamic")
{
val.style.display = val.isvalid ? "none" : "block";
return;
}
}
if ((navigator.userAgent.indexOf("Mac") > -1) && (navigator.userAgent.indexOf("MSIE") > -1))
{
val.style.display = "inline";
}
val.style.visibility = val.isvalid ? "hidden" : "visible";
}
</script>

I was about to try a css solution, but after reading what you posted (updated), I think I may stick with mine. I already had to configure my validator on the server for other reasons, so I just check the control type of the "controlToValidate", then for textbox type controls, I add a <br /> tag to the front of the message.
e.g.
// Inline (if configured)
myvalidator.Text = "<br />My message";
// Normal message and validation summary (if configured)
myvalidator.ErrorMessage = "My Message";
This keeps the line break from rendering in the validation summary, while still looking right for my inline messages.
I think Blackomen's approach is also good, but it needs to be selectively applied as well.

One option is to float the element to make the element act "more like a block".
HTML
<div class="form-group clearfix">
<asp:CustomValidator runat="server" Display="Dynamic" CssClass="help-block" />
</div>
CSS
span.help-block {
float: left;
width: 100%;
}

There is a simple solution which will work now and in the future.
1) Add a class to the validator
2) Use jquery to add an inner element to the validator span or use javascript
function wrapValidators() {
$('.input-error').wrapInner('<span class="block" />');
}
3) add css to 'block' class "display:block"

Just set float:left to your css
By using above solution if your required field display before your control then simply add new line tag <br/> between your control and required field validator

Related

How to make ASP CheckBoxList labels stay on same line as checkbox

This may be a common problem but I'm struggling to find a solution that will fix it
I have a modal popup I am displaying with jQuery, this popup contains a list of Checkboxes and a Button, the code looks like:
<div id="dialog" title="Notify Users" >
<div style="width:100%; height:500px; overflow:auto;">
<asp:CheckBoxList ID="chkNotify"
runat="server"
CssClass="checkboxlist_nowrap"
RepeatLayout="Table"
/>
</div>
<asp:Button ID="btnSaveNotifications"
runat="server"
Text="Ok"
/>
</div>
The popup displays correctly however the labels for each checkbox are on the line below the checkbox. I cant seem to figure out why this happens, at first I assumed that the div containing the CheckBoxList was simply too small so I gave each div a fixed width, but that didn't help anything.
I have also tried applying this CSS
.checkboxlist_nowrap tr td label
{
white-space:nowrap;
overflow:hidden;
width:100%;
}
It didnt help but im unsure about if the stylesheet actually was used even though I have:
<link href="../css/HelpDesk.css" rel="stylesheet" type="text/css" />
in my head tags.
Can anyone suggest anything else I can try?
Thanks
UPDATE: Here is my Jquery:
$(function () {
$("#dialog").dialog({
autoOpen: false,
show: "blind",
width: 400,
hide: "explode"
});
And here is how I populate the CheckBoxList:
Private Sub populateCheckBoxList()
Dim notificationList As DataTable
notificationList = dbGetNotificationsList(1)
For Each dr As DataRow In notificationList.Rows
Dim li As New ListItem
li.Text = dr("FullName")
li.Value = dr("ID")
If (dr("Checked") = 1) Then
li.Selected = True
Else
li.Selected = False
End If
chkNotify.Items.Add(li)
Next
End Sub
I have tried moving the CheckBoxList to just inside the form tag so that no other styles can be applied and nothing should affect it however I still get the same issue.
For me none of the above solutions worked and so i looked up the exact HTML rendered and found that the label had the display property set to block. Changing it to inline worked:
.checkboxlist_nowrap label
{
display:inline;
}
I'm thinking it's a CSS problem... I couldn't reproduce the whitespace wrapping with what you posted. You might want to make sure the width of your dialog is set correctly in jQuery.
Something like:
$("#dialog").dialog({
modal: true,
autoOpen: false,
draggable: false,
resizable: false,
width: 400,
buttons: {
Update: function () {
$(this).dialog('close');
},
Cancel: function () {
$(this).dialog('close');
}
}
});
Also, a really great way to check CSS (and javascript) is using Google Chrome's Dev Tools. They're packaged with Chrome. All you have to do is right-click on the element you're having trouble with and hover over the HTML in the window. It'll tell you all the classes being applied to it and will show you the margins/width/everything. It has been infinitely helpful for me.
I was having a similar problem. Found an answer on another stack overflow article which I have pasted below.
You want to have display:inline applied to the element that ASP generates to hold the label text, not the control itself. So, for example:
<style type="text/css">
label { display: inline-block; }
</style>
<asp:CheckBox Text="This text appears on same line as checkbox" runat="server" />
Using an ASP.NET checkbox control, I had the same problem with an unwanted linefeed between a checkbox and its label. I believe the problem reared its ugly head because this section of code was wrapped in a class that applied a {display: block} style. I solved the problem by first adding a CssClass attribute to the checkbox:
<asp:Repeater
ID="UserRoleList"
runat="server">
<Itemtemplate>
<asp:CheckBox
ID="RoleCheckBox"
CssClass="sameLine"
AutoPostBack="true"
Text='<%# Container.DataItem %>'
runat="server" />
<br />
</ItemTemplate>
</asp:Repeater>
Looking at the rendered html in the browser by viewing the source I saw that the style added a span and that the asp.net checkbox control was rendered within the span as an input tag and a label. I tried applying my style to just the span alone but it didn't work nor did applying the style to the input tag. What worked for me was applying the style to the label:
.sameLine label {
display: inline;
}
An article in code project says:
"The available text length for each CheckBox/RadioButton has been limited (I don’t know what’s causing the limitation), so the text will begin to wrap after 8 characters if you use multiple words. This is why the ‘white-space: nowrap’ is used in the CSS to eliminate that."
The Solution for the alignment issue is that you need to set the style property of the checkbox list tag as,
style="white-space:nowrap";
I think that should work for the plain HTML tags also.try using the same style statement in the css file too.
Here is the Link that i am sharing now Please refer to it.
Set property RepeatLayout = 'Flow' of CheckBoxList
By default, repeat layout is set to 'Table' due to that it comes to new line.
If layout is set to 'Flow' then checkboxes will be displayed on same line.
I had the same exact problem. For me, it was setting the width of the input to 100% in the css file that caused the problem. the checkbox control is made up of the input tag and the label tag. I set the input tag to take up 100% of the width and that caused the label tag to start from a new line. My advice is check your css file!
As long as this was the first link in google for this question - posting answer from another answered question Asp:CheckBox checkbox and text are not on the same line
Simple style display:inline-block; fixes issue. Of course, you'll want to keep in in CSS file, rather than in asp control properties. :)
<asp:CheckBox style="display:inline-block;" ID="CheckBoxShowParameters" runat="server" Text="Show Parameters" />
.checkboxlist_nowrap
{
white-space:nowrap;
display:inline-block;
}
<asp:CheckBoxList ID="CheckBoxList1" runat="server" CssClass="checkboxlist_nowrap" RepeatDirection="Horizontal">
.checkboxlist_nowrap label
{
font-weight:400;
padding-left:3px;
}
Use RepeatDirection property. This worked for me!!
Marking this as closed as I never managed to figure it out and the issue has been passed to another dev. Will post the answer here when I get it back.
I'd really appreciate people not down voting me for marking this as closed, I don't work at the company anymore, I have absolutely no way of recreating the issue or verifying any solutions people post and at the time I set this to closed none of the provided solutions fixed the problem.

Access Css of Asp:Button

So I want all buttons on my site to look the same and I need to edit a CSS file for them.
I was just wondering how you can access the css style of all controls named -asp:button.
Ie. Button { Font-size: 10px; } or #Button { Font-size: 10px; }
So far this is not working.
Most newer browsers support Attribute Selectors, so you could do something like
input[type="submit"] {
//styles here
}
You'll get better all around support by applying a class though as others have suggested.
ASP.NET Button controls render as:
<input type="submit">
You will need to give them a css class name that you can control in your css file.
In server side code:
myButton.CssClass = "myClass"
OR in ASPX markup:
<asp:Button CssClass="myClass" runat="server" ... />
CSS:
.myClass { width: 100px }
Edit having seen your comment:
To modify all buttons across the site you need to use Javascript, the jQuery library is extremely effective at this. If you were using jQuery you would just have this script on your Master page:
$(document).ready(function()
{
// Select all "input" controls with the type of "submit" and add your class to them
$(input[type="submit"]).addClass('myClass');
});
You can inclue CSS class in your asp:button code to give them a class and control their style:
<asp:button CssClass="mybuttons" />
Then you can use this class to style those buttons:
.mybuttons{
font-size:10px;
}
If you had more buttons that are not ASP.NET generated then this class only applies to buttons that are ASP.NET generated not others.
In .NET you need to provide a CSS class for your buttons. If you call it "Button1" for example, your CSS declaration would be:
.Button1 {
...
}
An ASP button is rendered in HTML as an INPUT of type="submit"... you can access all the buttons by using INPUT, but of course there are other INPUTS as well...
input {
font-weight: bold;
font-size: larger;
background-color: Red;
}

Regular Expression Validator - display block rather than inline when dynamic

Is there any way to make a RegularExpressionValidator render itself using display:block, instead of display:inline in its style attribute, when setting the Display property to "Display='Dynamic'"?
I have tried setting it in the stylesheet but this gets overwritten when it is rendered on the page.
Thanks
The idea above on using a css with !Important was so close I could taste it. Using that idea and CSS attribute selectors I did it. I had to use the "contains" selector to get it working in FF, but now I have tested it in IE10, FF and Chrome and so far it is working. It is really simple. Here is a sample validator in my aspx page
<asp:RequiredFieldValidator runat="server" ID="rfvRequired" ErrorMessage="This is required.<br/>This is line 2" ControlToValidate="tbRequired" ValidationGroup="CommonAttributesValidationGroup" SetFocusOnError="True" CssClass="valerror" Display="Dynamic"></asp:RequiredFieldValidator>
Next I have a style for valerror.
span.valerror[style*="inline"]
{
display:block !Important;
background-color: Yellow;
border: 1px solid #cccccc;
font-size:.9em;
}
That is it. how it works: when the span changes the style from "display:none" to "display:inline" the attribute selector on the span kicks in and forces it to be a block. You just need to make ONE css entry like the one above and make sure you make each validator that class.
Just wrap the validator in a div:
<div><asp:RegularExpressionValidator id="x" runat="server"></div>
I've found the only way to have the control not take up space when it is hidden and also display block is to put a <br /> tag after each validator.
So initially we have this:
Then if there is an error it looks like this:
How about using !important in the CSS class?
I've found a solution that solves this using a template control:
<asp:RequiredFieldValidator runat="server" EnableClientScript="True" Display="Dynamic" >
<TemplateControl>
<span class="error">This field is required.</span>
</TemplateControl>
</asp:RequiredFieldValidator>
CSS:
.error{position:relative;display:block;}
The resulting html is a bit messy, but it allows a display:block that pushes the validation into the next line;
<span id="ctl00_###" style="color: red; display: inline; ">
<templatecontrol>
<span class="error">This field is required.</span>
</templatecontrol>
</span>
Works with .Display = ValidatorDisplay.Static for me, didn't set EnableClientScript to true.
Update 1 and affecting cssClass with a class having display: block; to each regValidator
Update 2 forget about what I wrote before, I guess you don't care now about this but for others I would say, I think it's a forget of MS about regExpVal to not respond to display: block cause customValidator seems to work..
So for the regExpValidator I found that putting clear:left; and float:left works, and if the element under them moves while errors appears, you put clear: left on it.
ASP.NET injects a javascript file with validation code, it's the second script tag after the form tag in the HTML. This contains a function "ValidatorUpdateDisplay" that is called to show/hide validation messages. This can be overridden to use different javascript to show/hide e.g. if you are using jquery:
ValidatorUpdateDisplay = function (val) {
// Show/hide this validator's error message
if (val.isvalid){
$(val).hide();
} else {
$(val).show();
}
}
Or in your case:
ValidatorUpdateDisplay = function (val) {
// Show/hide this validator's error message
if (val.isvalid){
val.style.display = 'none';
} else {
val.style.display = 'block';
}
}
Simply put this code into a script tag after the ASP.NET form opening tag. Note this will affect all validators on the page, and ignores whether Display is set to Dynamic - if you wanted to support this you could extend it with code from the original function or custom code to check the type of validator.
Also see this question Can you have custom client-side javascript Validation for standard ASP.NET Web Form Validators?

Difference between Class vs CSSClass in ASP.Net CSS + CSS syntax question

What is the difference between:
<asp:GridView CssClass="someclass"
and
<table class="someclass">
And how does it relate to how one defines CSS?
For example, using CssClass, one can (I think) write CSS like so:
.someclass {font-family:"arial";
background-color:#FFFFFF;
width: 100%;
font-size: small;}
.someclass th {background: #7AC142;
padding: 5px;
font-size:small;}
But using class, it seems this syntax doesn't work, and judging from http://www.w3.org/TR/css3-selectors/#class-html I would have to write the above like this:
.someclass {font-family:"arial";
background-color:#FFFFFF;
width: 100%;
font-size: small;}
th.someclass {background: #7AC142;
padding: 5px;
font-size:small;}
Can someone shed some light on which is the correct way, or if they are both correct, but there is a difference between class and CssClass in ASP.Net?
UPDATE
Ok, looks like they are the same thing....so, are the above syntaxes both correct when using class or cssclass, because they don't seem to be.
ASP.Net CssClass is an abstract wrapper around the css "class" specifier.
Essentially, for most intents and purposes, they are the same thing. When you set the CssClass property to some string like "someclass", the html that the WebControl will render will be class = "someclass".
EDIT: The CSS selectors you have written are both "correct", but they do two different things. ".someclass th" matches any descendant th element of an element that has the "someclass" class. The second one matches the th element itself that has the "someclass" class.
Hope that's clear. Regardless of the way you specify the class for the elements (using ASP.Net's CSSClass, or just setting the class), your CSS selectors will do the same thing. They don't have anything to do with ASP.Net specifically.
Actually, there is a difference between class and CssClass: the class will not be seen by the code behind, but the CssClass will.
Thus, if you add a new class to a control in your code behind, for example:
myControl.CssClass += " foo";
while your control is set as follows:
<asp:TextBox class="Text" ID="myControl" runat="server" />
(Note class attribute: class="Text")
When inspecting your rendered element in your browser, you will see that it will be rendered as follows:
<input class=" foo" name="ctl00$MainContent$myControl" type="text" id="MainContent_myControl" >
(Note how the class has been overridden: class= " foo".)
If you set the CssClass on the other hand:
<asp:TextBox CssClass="Text" ID="myControl" runat="server" />
you will get it rendered (as expected) like so:
<input class="Text foo" name="ctl00$MainContent$myControl" type="text" id="MainContent_myControl">
(note the class has now both classes set, as expected! class="Text foo")
When you use the CssClass attribute on an ASP.NET server control, it will render out as class in the HTML.
For example, if I were to use a label tag in my mark up:
<asp:label runat="server" CssClass="myStyle" AssociatedControlID="txtTitle" />
would render to:
<label class="myStyle" for="txtTitle" />
There is no difference between the CssClass and class in Asp.Net other than the CssClass is a property of the Control and class is an attribute specified in the html. CssClass is rendered as the class attribute in Html.
Also note that CssClass="someclass anotherclass" works too as the string is carbon copied.
so, are the above syntaxes both
correct when using class or cssclass,
because they don't seem to be.
I am not sure what you mean when you say they do not "seem" to be correct? Do they render differently, even when you are using <table class='someClass'> in both cases?
IMHO, as far as the 'class' attribute is concerned, they are both correct. Did you try .someClass > th instead of .someClass th in the second case? That might solve the problem.

ASP.NET control with CSS visibility:hidden, not being shown on Control.Visible = true

I have a few labels on my page with a class of 'error', the rule for .error is:
.error {
color:Red;
visibility:hidden
}
The markup for the labels is:
<asp:Label ID="lblError" runat="server" CssClass="error" ></asp:Label>
I then set the .Text property of the error label in my code behind.
If I use lblError.Visible = True when I set the text, the label isn't shown. Any ideas why that would be? I'm maybe wrong here but I thought that setting .Visible was like setting the visibility style?
The Visible property affects rendering of the entire element and is unrelated to the CSS visibility attribute. When false, Visible when prevent any HTML from being rendered at all.
To change the css attribute, you will need to do it manually. You can do this by either removing the "error" class from the element (via the CssClass property) or by setting a style="visibility: visible" attribute manually via the Attributes property (since the style attribute overrides a css class):
control.Attributes["style"] = "visibility: visible";
You are getting confused between CSS visibility and the control's server side Visible property. To understand it better I recommend you create a sample page with a label, toggle the Visible property between true and false and view the generated HTML.
What you will find is as follows. As true:
<div>
<label runat="server" visible="true">Hello</label>
</div>
Will render:
<div>
<label>Hello</label>
</div>
When set to false, it will render:
<div>
</div>
Have a look at this page, it should clarify things:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.style.aspx
As written before:
The Visible property is serverside and determines if the Server will render the control or not (if it's not rendered, no HTML will be created for it, and it's not in the final HTML send to the client).
The Style property controls the style attribute of the element. The element will be rendered but you can control the visibility (CSS).

Resources