Search code examples
javascripthtmlrazor-pages

Getting data from a .cs file to a .cshtml


I'm trying to pass the data received from my function to a .cshtml file that uses javascript.

public static int LastID()
        {
            int LastArticleNr;
            SqlConnection conn = GetSqlConnection(null);

            conn.Open();
            LastArticleNr = conn.QueryFirstOrDefault <int> ("SELECT CAST(isnull(last_value,0) AS INT) AS ID FROM sys.identity_columns WHERE object_id = OBJECT_ID('Artikel')");
            conn.Close();

            return LastArticleNr;
        }

Now I don't know whether this is possible or not, or whether I would need to use a different method of getting this data. However what I've tried is simply calling the function which, to probably no-ones surprise didn't do much. I've also tried this:

@using namespace.Classes.DataLayer;
@{
var LastID = DataLayer.LastID();
}

However even if the using clause should include the class in which this function exists, it fails to recognise the DataLayer class.


Solution

  • It really depends on how your application is structured. Like: What error do you get when you try to access the Data Access Layer? But If this is being done on page load, you could pass the data into TempData:

    TempData['LastId'] = LastID();
    

    And then in your razor page:

    @{
        var lastId = TempData['LastId'];
      }
    

    However if you wanted to get it at any time after the page has loaded and do not want to refresh the page, you would have make an ajax call