繁体   English   中英

如何在MVC Razor View中分配和使用变量

[英]How to assign and use variable in MVC Razor View

我已经确定了一些需要一些简单逻辑的视图,例如将一个类添加到用@Html帮助器创建的一组控件中。 我尝试了几种不同的方法,但是他们要么在视图中抛出错误,要么就是不工作。

一个简单的例子:

分配变量:

@if( condition )
{
    var _disabled = "disabled";
}

@Html.CheckBoxFor(m => m.Test, new { @class = "form-control " + @_disabled })

要么:

@if( condition )
{
    var _checked = "checked";
}

@Html.CheckBoxFor(m => m.Test, new { @checked = @_checked })

当然,这些都行不通。 我只是想在我的视图中消除一堆@if条件,但我有其他轻量级逻辑用于使用变量。 我的问题可能更多的是如何以这种方式使用变量而不是实际分配它?

看起来你理解剃刀很好。 您的代码的问题似乎是您使用的变量超出了范围。 您不能在if语句中定义变量,然后在外部使用它,因为编译器不会确定外部变量实际存在。

我建议如下:

@{
var thing = "something";//variable defined outside of if block. you could just say String something; without initializing as well.
    if(condition){
        thing = "something else";
    }
}
@Html.Raw(thing);//or whatever

作为旁注,(在我看来)最好在控制器中做一些事情,而不是视图。 但如果事情在意见中更有意义,那就把它们放在那里。 ( - :

希望这可以帮助。

试试这个;

@{
    var disabled = string.Empty;
    if (true)
    {
        disabled = "disabled";
    }
}
@Html.CheckBoxFor(m => m.RememberMe, new { @class = "form-control " + disabled })

谢谢!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM