Using ternary operator to output a string containing whitespace in Razor - asp.net

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

Related

Cannot implicitly convert type "string" to "bool" when using if condition?

When I write if condition in one line for the textbox i.e.
if (txtNotes.Text.Equals(" ") ? string.Empty: gvrow.Cells[6].Text)
I am getting the error stating:
Cannot implicitly convert type "string" to "bool"
Just want to check where I am going wrong.
You're confusing the standard if statement syntax with the ternary operator ?:. It's either:
txtNotes.Text = txtNotes.Text.Equals(" ") ? string.Empty : gvrow.Cells[6].Text;
or
if (txtNotes.Text.Equals(" "))
{
txtNotes.Text = string.Empty;
}
else
{
txtNotes.Text = gvrow[6].Cells.Text;
}
Edit: from your comment you've stated your setting the value of txtNotes.Text, so I recommend using the ternary operator to achieve this.

Asp.net mvc razor view string.format does not seems to work

I am using string.format to format my model value inside razor view but it does not gives desired result
#string.Format("{0:00}", Model.Range == null ? "" : Model.Range.ToString())
It should result as 05
if i am using below it gives me result but not from model
#string.Format("{0:00}", 5)
Someone have any idea or same experience ?
If Model.Range is a number type then you need to write:
#string.Format("{0:00}", Model.Range == null ? "" : Model.Range)
because with the Model.Range.ToString() you have converted your Range to string so the number formatting cannot be applied because it is not a number anymore.
By the way string.Format handles null arguments so it is enough to write:
#string.Format("{0:00}", Model.Range)
If Model.Range is not a number but with Model.Range.ToString() you get a number in a string representation then you need to first convert it to a number (like using int.Parse or its other variants) then you can pass the number to string.Format which can now apply the correct formatting.

xQuery substring problem

I now have a full path for a file as a string like:
"/db/Liebherr/Content_Repository/Techpubs/Topics/HyraulicPowerDistribution/Released/TRN_282C_HYD_MOD_1_Drive_Shaft_Rev000.xml"
However, now I need to take out only the folder path, so it will be the above string without the last back slash content like:
"/db/Liebherr/Content_Repository/Techpubs/Topics/HyraulicPowerDistribution/Released/"
But it seems that the substring() function in xQuery only has substring(string,start,len) or substring(string,start), I am trying to figure out a way to specify the last occurence of the backslash, but no luck.
Could experts help? Thanks!
Try out the tokenize() function (for splitting a string into its component parts) and then re-assembling it, using everything but the last part.
let $full-path := "/db/Liebherr/Content_Repository/Techpubs/Topics/HyraulicPowerDistribution/Released/TRN_282C_HYD_MOD_1_Drive_Shaft_Rev000.xml",
$segments := tokenize($full-path,"/")[position() ne last()]
return
concat(string-join($segments,'/'),'/')
For more details on these functions, check out their reference pages:
fn:tokenize()
fn:string-join()
fn:replace can do the job with a regular expression:
replace("/db/Liebherr/Content_Repository/Techpubs/Topics/HyraulicPowerDistribution/Released/TRN_282C_HYD_MOD_1_Drive_Shaft_Rev000.xml",
"[^/]+$",
"")
This can be done even with a single XPath 2.0 (subset of XQuery) expression:
substring($fullPath,
1,
string-length($fullPath) - string-length(tokenize($fullPath, '/')[last()])
)
where $fullPath should be substituted with the actual string, such as:
"/db/Liebherr/Content_Repository/Techpubs/Topics/HyraulicPowerDistribution/Released/TRN_282C_HYD_MOD_1_Drive_Shaft_Rev000.xml"
The following code tokenizes, removes the last token, replaces it with an empty string, and joins back.
string-join(
(
tokenize(
"/db/Liebherr/Content_Repository/Techpubs/Topics/HyraulicPowerDistribution/Released/TRN_282C_HYD_MOD_1_Drive_Shaft_Rev000.xml",
"/"
)[position() ne last()],
""
),
"/"
)
It seems to return the desired result on try.zorba-xquery.com. Does this help?

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.

ASP conditional error

i am trying to use an ASP conditional here:
if (Request.Cookies("username")) and
(Request.Cookies("password")) <> ""
Then
And i keep getting this error:
Type mismatch: '[string: ""]'
Any ideas what I am getting that?
try
if (Request.Cookies("username") <> "") and (Request.Cookies("password") <> "") Then
Actually, I would do the following..
if (!string.IsNullOrEmpty(Request.Cookies("username")) &&
!string.IsNullOrEmpty(Request.Cookies("password")))
{
// Do your stuff, here :)
}
Get into the habit of using string.IsNullOrEmpty for testing variables and string.Empty for setting values, if u don't want a string to be null.

Resources