I have a variable named wURL which contains a URL. If the URL is NULL I would like to not have the onclick Event in my TD. My trouble is figuring out how to do this in razor syntax:
<td class="" onclick="window.open('@wURL', '_blank')">
I'm thinking it should be something like this:
<td class="" (@wURL ?){ onclick="window.open('@wURL', '_blank')"}>
But This doesn't work. What is the correct way to write this?
尝试这个:
<td @(Html.Raw(wURL == null ? "" : $"onclick=\"window.open('{wURL}', '_blank')\"")) >
I'll leave this here for those who want to display different elements switch a condition with razor :
@if(condition){
<td onclick="window.open('@wURL','_blank')">...</td>
}
else{
<td >...</td>
}
However, if you want only a part of it to be different, then you'll find the other answers more suitable.
@{string oc = wURL == null ? "" : "onclick=window.open('" + @wURL + "','_blank')";}
<td class = "" @oc>
At request of questioner I'll break down the ternary into a simpler if-else statement for clarification:
@{ // start a c# block
string oc; // create a string variable
if wURL == null { //before I used a "ternary" conditional, but this compiles to the same thing
oc = ""; // if wURL is null set oc to empty string, so nothing will be written in the tag
}
else
{
oc = "onclick=window.open('" + @wURL + "','_blank')"; // set the onclick to open a window with the wURL variable
}
}
<td class = "" @oc>
<!-- If the oc variable is empty, nothing will be written after class modifier, otherwise you'll get the onclick statement -->
To see how the if-else statement can be compacted into the ternary in the original example look here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.