How to use ? : if statements with Razor and inline code blocks - asp.net

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.

Related

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 determine css's class with if statement

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

Using ternary operator to output a string containing whitespace in Razor

I'm trying to use a ternary operator in Razor, similar to this question, but what I want to output contains whitespace. This code
#(selectedGoal == null ? "" : "value=" + selectedGoal.Name)
should produce
value="Goal 3"
as the value of selectedGoal.Name is "Goal 3". Instead, I get
value="Goal" 3
which is no good. I've tried a bunch of different combinations of escaped quotes, # symbols and no # symbols, and I just can't get this to work, i.e.
#(selectedGoal == null ? "" : "value=" + "selectedGoal.Name")
#(selectedGoal == null ? "" : "value=#selectedGoal.Name")
and then I just get something like
value="selectedGoal.Name"
Anyone know how this should be done?
Your value attribute is missing its own quotes, so they are being automatically added before the space. Try moving value outside of the expression.
value="#(selectedGoal == null ? "" : selectedGoal.Name)"
What about
#(selectedGoal == null ? "" : "value=\"" + selectedGoal.Name + \")
Or you can try rendering them directly as an HTML block, using my method on
Html literal in Razor ternary expression

How can I tell if E4X expression has a match or not?

I am trying to access an XMLList item and convert it to am XML object.
I am using this expression:
masonicXML.item.(#style_number == styleNum)
For example if there is a match everything works fine but if there is not a match then I get an error when I try cast it as XML saying that it has to be well formed. So I need to make sure that the expression gets a match before I cast it as XML. I tried setting it to an XMLList variable and checking if it as a text() propertie like this:
var defaultItem:XMLList = DataModel.instance.masonicXML.item.(#style_number == styleNum);
if(defaultItem.text())
{
DataModel.instance.selectedItem = XML(defaultItem);
}
But it still give me an error if theres no match. It works fine if there is a match.
THANKS!
In my experience, the simplest way to check for results is to grab the 0th element of the list and see if it's null.
Here is your code sample with a few tweaks. Notice that I've changed the type of defaultItem from XMLList to XML, and I'm assigning it to the 0th element of the list.
var defaultItem:XML =
DataModel.instance.masonicXML.item.(#style_number == styleNum)[0];
if( defaultItem != null )
{
DataModel.instance.selectedItem = defaultItem;
}
OK I got it to work with this:
if(String(defaultItem.#style_number).length)
Matt's null check is a good solution. (Unless there is the possibility of having null items within an XMLList.. probably not, but I haven't verified this.)
You can also check for the length of the XMLList without casting it to a String:
if (defaultItem.#style_number.length() > 0)
The difference to String and Array is that with an XMLList, length() is a method instead of a property.

Regular expression to convert substring to link

i need a Regular Expression to convert a a string to a link.i wrote something but it doesnt work in asp.net.i couldnt solve and i am new in Regular Expression.This function converts (bkz: string) to (bkz: show.aspx?td=string)
Dim pattern As String = "<bkz[a-z0-9$-$&-&.-.ö-öı-ış-şç-çğ-ğü-ü\s]+)>"
Dim regex As New Regex(pattern, RegexOptions.IgnoreCase)
str = regex.Replace(str, "<font color=""#CC0000"">$1</font>")
Generic remarks on your code: beside the lack of opening parentheses, you do redundant things: $-$ isn't incorrect but can be simplified into $ only. Same for accented chars.
Everybody will tell you that font tag is deprecated even in plain HTML: favor span with style attribute.
And from your question and the example in the reply, I think the expression could be something like:
\(bkz: ([a-z0-9$&.öışçğü\s]+)\)
the replace string would look like:
(bkz: <span style=""color: #C00"">$1</span>)
BUT the first $1 must be actually URL encoded.
Your regexp is in trouble because of a ')' without '('
Would:
<bkz:\s+((?:.(?!>))+?.)>
work better ?
The first group would capture what you are after.
Thanks Vonc,Now it doesnt raise error but also When i assign str to a Label.Text,i cant see the link too.Forexample after i bind str to my label,it should be viewed in view-source ;
<span id="Label1">(bkz: here)</span>
But now,it is in viewsource source;
<span id="Label1">(bkz: here)</span>

Resources