How to determine css's class with if statement - asp.net

<div class="<%#((int)Eval("Cevaplanma_Sayisi")>0) ? "divcevaplanmasayisiozel" : "divcevaplanmasayisinormal" %>">
my code is above.the code runs when I use access database but it doesnt run with sqlserver2008 where is the error.it says when I runs the code invalid exception handled

Try this:
<div class='<%#(((int)Eval("Cevaplanma_Sayisi"))>0) ? "divcevaplanmasayisiozel" : "divcevaplanmasayisinormal" %>'>
The first problem is that you need to convert the object value of "Cevaplanma_Sayisi" into int.
The second problem is that you must wrap the Eval statement within ' and ', otherwise you get malformed html.

Related

How do you handle NULL values in DataBound controls?

I am trying to limit the characters displayed in ASP.NET Label controls that have their Text values databound to a SQL Database. If the field in the database is not NULL, I do not have any trouble. If they are NULL, I get the exception "Object reference not set to an instance of an object."
My code is as follows:
<asp:Label ID="LabelDescriptionLabel" runat="server" Text='<%# IIf(Not IsDBNull(Item.LabelDescription), IIf(Item.LabelDescription.ToString.Length > 30, Left(Item.LabelDescription, 30) & "...", Item.LabelDescription), Item.LabelDescription)%>' />
I have also tried the following, without any luck:
<asp:Label ID="LabelDescriptionLabel" runat="server" Text='<%# IIf(Not IsNothing(Item.LabelDescription), IIf(Item.LabelDescription.ToString.Length > 30, Left(Item.LabelDescription, 30) & "...", Item.LabelDescription), Item.LabelDescription)%>' />
I am using ASP.NET with VB.NET. I have tried using the CSS "text-overflow: ellipsis" method as well, but I had some table formatting issues that I have not resolved.
Is there a way to handle these NULL values and prevent run-time exceptions?
Thanks!
One problem you are having is that the old IIF is a function which evaluates all the parts before it decides what to return.
IIF(Not IsDBNull(Item.LabelDescription), TruePart, FalsePart)
It does not matter if the expression is true or not, the TruePart and
FalsePart statements will always be executed. Since they include references to something which may be DBNull/Nothing/null, you get an error.
Something else though is that Nothing is not the same as DBNull, and if Item is an Object which can be Nothing/null, then testing the description of Nothing/null will be problematic.
The If Operator has been available since abut 2008. The structure is the same but it only evaluates the test condition and the True or False expression which applies:
If( Condition, TruePart, FalsePart )
The "short circuiting" prevents the expression/Part which does not apply from being evaluated. As long as the rest of the code is valid, you should be able to just clip one of the Is from the IIF functions.
Since you want to the object Nothing I would use the Nothing keyword rather than the VB IsNothing function:
If(Item IsNot Nothing),
If(Item.LabelDescription.ToString.Length > 30, x, y), y)
The If operator is not the same as the If/Then/Else statement block.

Primefaces datatable, nested conditional row coloring

I'm using PF 3.4.1 and JSF.
I would like to have a conditional selection of the css rowclass depending on two conditions:
One style should be for objects that are disabled, and one for objects that are expired.
I was able to put this two conditions in the same time, but, obviously, this cause a redundancy of css classes. I would like to have an overwrite of the classes in order to have predominance of the css class of disabled objects on expired objects.
Should look like this structure:
if (expired){
if (disabled){
return css1;
}
return css2
}
However, that is the code:
<p:dataTable id="results" var="utente" value="#{searchController.userList}"
paginator="true" rows="10"
rowStyleClass="#{user.expDate le user.currentDate ? 'rowdatatable3' : 'rowdatatable2'} #{user.enabled eq 'FALSE' ? 'rowdatatable1' : 'rowdatatable2'}"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="10,25,50">
rowdatatableX are css styles.
With this code, results have always rowdatatable2 or rowdatable1 and never the 3rd option.
My idea was something like this:
rowStyleClass="#{user.expDate le user.currentDate ? #{user.enabled eq 'FALSE' ? 'rowdatatable1' : 'rowdatatable3'} : 'rowdatatable2'} "
..but it doesn't work.
Please help to find a solution. Thanks.
Try writing a method in your Bean (or transient method in user entity) that compares 2 dates expDate and currentDate
public boolean isExpired() {
return getExpDate.before(getCurrentDate);
}
If user.enabled is of type boolean skip the FALSE comparison. Since your table variable is utente you should use it! Your expression should look like that
"#{utente.expired ? (utente.enabled ? 'rowdatatable1' : 'rowdatatable3') : 'rowdatatable2'}"
so:
IF expired AND enabled -> 'rowdatatable1'
IF expired AND disabled -> 'rowdatatable3'
IF NOT expired -> 'rowdatatable2'

How to verify value of text field in Symfony 1.4 functional tests

I am trying to use Symfony 1.4's functional tests (sfTextFunctional) to verify the value of a textfield is as I expect. This is the html that is generated
<input type="text" maxlength="10" name="number_plant[1]" value="5" id="number_plant_1">
During the test I can set the value easily
setField('number_plant[1]', '5')->
And I have tried the following permutations of checkelement but they all return null
checkElement('number_plant[1]',"5")->
checkElement('number_plant_1',"5")->
checkElement('#number_plant_1',"5")->
checkElement('form input[type="text"][name="number_plant[1]"]',"5")->
Try something like:
checkElement('#number_plant_1[value="5"]')
EDIT: Apparently only this selector works as expected:
checkElement('form input[type="text"][name="number_plant[1]"][value="5"]')
(which is quite strange ;) )
This will check if an elemnt with id = "number_plant_1" and value = "5" exists on the page. As far as I know when you pass a string as the second parameter to checkElement it will try to match the content of the found element with the given string.

How to use ? : if statements with Razor and inline code blocks

I'm updating my old .aspx views with the new Razore view engine. I have a bunch of places where I have code like this:
<span class="vote-up<%= puzzle.UserVote == VoteType.Up ? "-selected" : "" %>">Vote Up</span>
Ideally I'd like to do this:
<span class="vote-up#{puzzle.UserVote == VoteType.Up ? "-selected" : ""}">Vote Up</span>
However there's two problems here:
vote-up#{puzzle.UserVote .... is not treating the # symbol as a start of a code block
#puzzle.UserVote == VoteType.Up looks at the first part #puzzle.UserVote as if it's supposed to render the value of the variable.
Anyone know how to address these issues?
This should work:
<span class="vote-up#(puzzle.UserVote == VoteType.Up ? "-selected" : "")">Vote Up</span>
#( condition ? "true" : "false" )
The key is to encapsulate the expression in parentheses after the # delimiter. You can make any compound expression work this way.
In most cases the solution of CD.. will work perfectly fine. However I had a bit more twisted situation:
#(String.IsNullOrEmpty(Model.MaidenName) ? " " : Model.MaidenName)
This would print me " " in my page, respectively generate the source &nbsp;. Now there is a function Html.Raw(" ") which is supposed to let you write source code, except in this constellation it throws a compiler error:
Compiler Error Message: CS0173: Type of conditional expression cannot
be determined because there is no implicit conversion between
'System.Web.IHtmlString' and 'string'
So I ended up writing a statement like the following, which is less nice but works even in my case:
#if (String.IsNullOrEmpty(Model.MaidenName)) { #Html.Raw(" ") } else { #Model.MaidenName }
Note: interesting thing is, once you are inside the curly brace, you have to restart a Razor block.

Why does my repeater keep crashing on Eval(NULL) values?

<asp:Repeater ID="rptLessons" runat="server">
<ItemTemplate>
<tr>
<td><%#Eval("fullname")%></td>
<td><%#isCompleted(Eval("totallessons"), Eval("completedlessons"), Eval("totalNumAvail"), Eval("totalNumCorrect"))%></td>
<td><%#FormatPercent(Eval("totalnumcorrect") / Eval("totalNumAvail"))%> <%-- (<%#Eval("totalnumcorrect")%> / <%#Eval("totalNumAvail")%>) --%></td>
<td><%#FormatPercent(Eval("completedlessons") / Eval("totallessons"))%> <%-- (<%#Eval("completedlessons")%> / <%#Eval("totallessons")%>) --%></td>
<td><%#Eval("lastaccessed")%></td>
</tr>
</ItemTemplate>
</asp:Repeater>
I can't figure it out but as soon as it hits some NULL data it refuses to move on to drawing the next elements.
You need to give a stack trace to be sure.
But I can see several issues:
DIV#0 errors inside FormatPercent
NULL errors.
Example Solution
(System.Convert.ToInt32 should convert DBNull/NULL to 0)
Or alter isCompleted to accept Object paramters and do your NULL / DBNull checking inside the function.
On slightly different approach that might be helpful would be to do your computations in your code behind rather than inline in the markup. Just easier to check for nulls etc. I almost always go down this path with anything other than a simple Eval() in my markup.
<td>
<%#GetCorrectPercent()%>
</td>
protected string GetCorrectPercent()
{
if(Eval("totalnumcorrect") == null || Eval("totalNumAvail") == null)
return "n/a";
return ((int)Eval("totalnumcorrect") / (int)Eval("totalNumAvail")).ToString();
}
Not sure all the formatting is correct here but this should get you going in a different direction. Eval() will work within the called methods so long as the caller is current performing a DataBind().
If I had to guess, I would say that your isCompleted function doesn't handle values of Nothing. This is a guess because the function hasn't been listed in your example.
I tend more towards the explicit. Forgive any minor mistakes in the code, I'm not able to test this.
If in your markup you swap out those evals for literals then in the code behind:
If you have a collection of MyClass.
In your page's init event
this.rptLessons.OnItemDataBound += rptLessons_DataBound...
In the load or where ever you choose
this.rptLessons.DataSource = CollectionOfMyClass;
this.rptLessons.DataBind();
Then in that itemDataBoundEvent
MyClass myClass = (MyClass)ri.DataItem;
Literal litFullname = FindControl(ri, "litFullName");
litFullName.Text = myClass.Fullname;
This way you can cater for nulls etc in a more controlled way than using eval.

Resources