Reputation: 3707
I have the following code in a Razor view where I want to only display an address if the first piece is available.
@if (!string.IsNullOrWhiteSpace(Model.Address1))
{
@Model.Address1<br />
@Model.Address2<br />
@Model.City, @Model.State @Model.Zip
}
However, it's giving me a design time error saying "Can not use local variable 'Model' before it is declared".
I've done some searching on the syntax and as far as I can tell it looks correct but obviously I'm missing something. Can anyone see why this would work?
UPDATE
It's a little clunky looking but this is what I ended up with.
@if (!string.IsNullOrWhiteSpace(Model.Address1))
{
@:@Model.Address1<br />
if (!string.IsNullOrWhiteSpace(Model.Address2))
{
@:@Model.Address2<br />
}
@:@Model.City, @Model.State @Model.Zip
}
Upvotes: 0
Views: 52
Reputation: 887453
You're writing HTML which is being parsed as C# code, with confusing results.
The contents of a code block (such as @if
) are parsed as code, not HTML.
Therefore, @Model.City, @Model.State @Model.Zip
becomes a malformed variable declaration.
You need to wrap it in an HTML tag or <text>
, or prefix each line with @:
.
Upvotes: 1