Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

c# - How can I use a variable in the ASP.NET/Blazor _Layout.cshtml that I created in a different class?

I am SO NEW to ASP.NET/Blazor. I have been a Java guy for MANY years and have had to switch to this new technology, so please bear with me.

I have a "Constants" class Constants.cs:

namespace MyAwesomeApplication.Web.Classes{
    public class Constants{
        public const String myString01 = "the quick brown fox";
        public const String myString02 = "jumps over the lazy dog";
    }
}

Now in my _Layout.cshtml page I would like to use those constants, but I do not know how to do it.

<div>
    @{// Use my constant here}
</div>

I tried a Google search, but didn't come up with much help.


EDIT: I have tried this:

<div>
    @{MyAwesomeApplication.Web.Classes.Constants.myString01}
</div>

And received the error:

CS0426: The type name 'myString01' does not exist in the type 'Constants'.
question from:https://stackoverflow.com/questions/65904048/how-can-i-use-a-variable-in-the-asp-net-blazor-layout-cshtml-that-i-created-in

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Was going to say the same as gunr2171..

<div>
@(MyAwesomeApplication.Web.Classes.Constants.myString01)
</div>

, will write the text.

Or you can write it as:

<div>
@MyAwesomeApplication.Web.Classes.Constants.myString01
</div>

But if you want to do some string concationation, you need to use paranteses () for response write:

<div>
@(MyAwesomeApplication.Web.Classes.Constants.myString01 + " " + MyAwesomeApplication.Web.Classes.Constants.myString02)
</div>

Or with a code-block:

@{ 
string print = MyAwesomeApplication.Web.Classes.Constants.myString01 + " " + MyAwesomeApplication.Web.Classes.Constants.myString02
}
<div>
@print
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...