[英]Conditional OnClick With Razor in MVC C#
I have a variable named wURL which contains a URL. 我有一个名为wURL的变量,其中包含一个URL。 If the URL is NULL I would like to not have the onclick Event in my TD.
如果URL为NULL,我希望在TD中没有onclick事件。 My trouble is figuring out how to do this in razor syntax:
我的麻烦是弄清楚如何用razor语法做到这一点:
<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 : 对于那些想要显示不同元素并使用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: 应发问者的要求,我将三元分解成一个更简单的if-else语句进行澄清:
@{ // 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 . 要了解如何在原始示例中将if-else语句压缩为三进制,请参见此处 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.