Reputation: 2077
I know I must be being stupid here, but I can't work out why this code isn't working. I'm very new to Razor, so please go easy on me.
I have the following code in my markup: (I've cut it down to be as simple as I can make it while still reproducing the issue so that I can hopefully diagnose the issue easier)
string testVar = "test";
@testVar
It returns the following:
error CS0103: The name 'testVar' does not exist in the current context
I've tried using different names for the variable, I've tried having it use "var" instead of "string" for it's declaration, I've tried assigning various different values to it, I've tried surrounding the variable in brackets like @(testVar)
, but the issue is still there. It's very frustrating, because in another part of my code I have
string prop = @p.Name + " (" + @p.PropertyType + ") - " + @p.GetValue(@page, null).ToString() + "\r\n";
@prop
which works fine.
I can't think what could be causing it, and it's starting to frustrate me.
Thanks,
YM
Upvotes: 9
Views: 16119
Reputation: 62498
In Razor when we want to write c# statements we have to tell it that from here c# code starts:
@{ // from here c# block starts
string testVar = "test";
} // here ends
Now if you want to access this variable in html you can do like this:
<span>@testVar</span>
When you are writing:
string prop = @p.Name + " (" + @p.PropertyType + ") - " + @p.GetValue(@page, null).ToString() + "\r\n";
it is considered as plain text and will be rendered on browser like "string prop = ..." you have to tell that it is c# code by following way:
@{
string prop = @p.Name + " (" + @p.PropertyType + ") - " + @p.GetValue(@page, null).ToString() + "\r\n";
}
Upvotes: 12