0

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.

1 Answers1

0

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

  • I only need to get it on page load and frankly, I don't understand ajax one bit. But it doesn't recognise LastID() within TempData. – Tim Verhees Apr 29 '21 at 07:40
  • Can I see how you set it? Share a code snippet please. – Daniel Oluwadare Apr 29 '21 at 17:04
  • fixed it by calling it as @TempData['LastId'] in the function for some reason it works there but not at the top of the file within @{ works now! – Tim Verhees Apr 30 '21 at 00:07
  • Yeah, you can use razor in any part of a .cshtml file(even in JavaScript although it's advisable), as long as you have @{}. I'm happy you're able to figure it out. – Daniel Oluwadare Apr 30 '21 at 15:23