开发者

Javascript MVC ASP.NET simple if condition not working

I've a following asp.net mvc razor view code which doesn't seem to be working:

@{ 
  bool Condition1=Model.SomeObject.Condition1;
  bool Condition2 = Model.SomeObject.Condition2;
}

if('@Condition1') {
    alert('hi condition1');
} else if ('@Condition2') {
 开发者_运维问答   alert('hi condition2');
} else { 
    alert('hi condition3'); 
} 

Here is what not working:

  1. when Condition2 is True the javascript 'hi condition2' never get hit.

I also tried with this below and still not working.

else if ('@Condition2' ==true){

Am I missing any casting here, please?

Thank you.


if(@Condition1) {
    alert('hi condition1');
} else if (@Condition2) {
    alert('hi condition2');
} else { 
    alert('hi condition3'); 
} 


Try:

if(@(Condition1.ToString().ToLower())) {}

C# boolean is True and js's is true.

What you have won't work as the text 'false' in js counts as a "truthy" value (empty string is falsey).


According to your code alert('hi condition2') should work only when Condition1 == false and Condition2 == true.
In addition, you shouldn't wrap @Condition1 and @Condition2 in quotes '. It is bool, not a string.
The matter is in JavaScript any condition with not empty string equals to true.
One more thing: .NET bool converts to string as True or False (in upper case). In other side, JS bool values are true and false.
So try:

if (@(Condition.ToString().ToLower())) { ... }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜