Cannot access conditional Razor variable as href

310 Views Asked by At

I have a razor view that generates a url based on some items returned by the model. When I create a url variable without any if statements, the url variable can be found and used as an href. However, when I have this code (using if statements) it says: "The name 'url' does not exist in the current context". How can I make this work?

       @{
    if(@Model.RootPageName != null)
    {     
         var abstractPage = Content.GetPage<AbstractPage>(@Model.RootPageName);
         var url = GenerateUrl(abstractPage);
    }
    else
    {
        var url = @Model.ButtonUrl;

    }
 }

<a href="@url" class="small button">@Model.ButtonText</a>
3

There are 3 best solutions below

0
On BEST ANSWER

Just move url so it's accessible outside of the if scope:

 @{
    string url;
    if(@Model.RootPageName != null)
    {     
         var abstractPage = Content.GetPage<AbstractPage>(@Model.RootPageName);
         url = GenerateUrl(abstractPage);
    }
    else
    {
         url = @Model.ButtonUrl;

    }
 }
0
On

Try to declare var url outside of "if" if you declare inside of if it's scope of life is inside of "if" or "else"

1
On

if you declare a variable nested inside of an If / else statement, the variable isn't declared for the rest of the code.

You have:

if(...)
{
   var url = "foobar";
 }

it needs to be:

string url;
if(...)"
{
 url = "foobar";
}