asp.net-mvc 如何在 MVC Razor 视图中分配和使用变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24582671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:45:53  来源:igfitidea点击:

How to assign and use variable in MVC Razor View

asp.net-mvcrazor

提问by rwkiii

I've identified several of my views that require some simple logic, for example to add a class to a set of controls created with @Html helpers. I've tried several different ways, but they either throw errors in the View or just don't work.

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

A simple example:

一个简单的例子:

Assign variable:

分配变量:

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

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

Or:

或者:

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

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

Of course, these doesn't work. I'm just trying to eliminate a bunch of @ifconditions in my Views, but I have other lightweight logic uses for using variables. My problem might be more of how to use a variable in this way than actually assigning it?

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

采纳答案by Hyman

It would seem that you're understanding razor fine. The problem with your code seems to be that you're using a variable out of scope. You can't define a variable inside an if statement, and then use it outside, because the compiler won't know for sure that the variable outside actually exists.

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

I would suggest the following:

我建议如下:

@{
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

As a side note, (in my opinion) it's better to do stuff in the controllers when you can, rather than the views. But if things make more sense in the views, just keep them there. (-:

作为旁注,(在我看来)最好在控制器中做一些事情,而不是在视图中。但是,如果视图中的内容更有意义,请将它们保留在那里。(-:

Hope this helps.

希望这可以帮助。

回答by Saranga

Try this;

尝试这个;

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

Thanks!

谢谢!