1

I'm trying to use a 2sxc view to create some statistics with linq. However I can't seem to be able to call any c# var. Here's an example:

@{
    if (@Request.QueryString["ano"] == "" || @Request.QueryString["ano"] == null) {
        <p>ano not set, using current year (@DateTime.Now.Year)</p>
        var year = @DateTime.Now.Year;
        } else {
        <p>ano set (@Request.QueryString["ano"])</p>
        var year = @Request.QueryString["ano"];
    }

    var items = AsDynamic(App.Data["entity"]);
    items = items.Where(p => Convert.ToDateTime(p.data_a).Year == year);
}

This results in

error CS0103: The name 'year' does not exist in the current context

Am I doing something really stupid again?

João Gomes
  • 276
  • 2
  • 11
  • 1
    Your `year` variable declared in inner scope. Move it decalration above `if` statement – Aleks Andreev Oct 15 '17 at 10:32
  • I don't quite get it... Shouldn't it be the same? var x= 1 and if (1=1) {var x=1}? Nevertheless, it works. Adding int year = 0; at the top and adapting requests to int fixed it. Thanks (would you please also post your comment as an answer to mark it solved?). – João Gomes Oct 15 '17 at 10:44

1 Answers1

2

You are declaring variable inside if statement and referencing it outside if
Now you can rewrite you code like this:

@{
    int year = 0;
    if (@Request.QueryString["ano"] == "" || @Request.QueryString["ano"] == null) {
        <p>ano not set, using current year (@DateTime.Now.Year)</p>
        year = @DateTime.Now.Year; // no "var" keyword here!
        } else {
        <p>ano set (@Request.QueryString["ano"])</p>
        year = int.Parse(Request.QueryString["ano"]);
    }

    var items = AsDynamic(App.Data["entity"]);
    items = items.Where(p => Convert.ToDateTime(p.data_a).Year == year);
}
Aleks Andreev
  • 6,732
  • 8
  • 27
  • 36