I need to do a few db things and I would rather have extension methods in a separate file rather than having them all within the cshtml file.
But, I get the following error:
Compiler Error Message: CS0120: An
object reference is required for the
non-static field, method, or property
‘UserOperations.GetFirstName(string)’
Which points me to this line:
Line 165: <li><a href="@Href("myaccount/account.cshtml")">Hi, @UserOperations.GetFirstName(WebSecurity.CurrentUserId)</a></li>
The code I’m using is: (CSHTML)
@if(WebSecurity.IsAuthenticated)
{
<li><a href="@Href("myaccount/account.cshtml")">Hi, @UserOperations.GetFirstName(WebSecurity.CurrentUserId.ToString())</a></li>
}
else
{
<li><a href="@Href("myaccount/Login.cshtml")">My Account</a>
<ul>
<li><a href="@Href("myaccount/Login.cshtml")">Sign In</a></li>
<li><a href="@Href("myaccount/Register.cshtml")" title="It's FREE!">Create Account</a></li>
</ul>
</li>
}
And…: (UserOperations.CS)
using System;
using WebMatrix.WebData;
using WebMatrix.Data;
using System.Collections.Generic;
using System.Web;
/// <summary>
/// User & Database-based operations in this file only.
/// </summary>
public class UserOperations
{
public string GetFirstName(string CurrentUserID)
{
WebSecurity.InitializeDatabaseConnection("eee", "www", "www", "www", true);
var database = Database.Open("OSF");
var SelectQueryString = "SELECT FirstName FROM UserProfile WHERE FirstName = " + CurrentUserID;
var result = database.Query(SelectQueryString);
return result.ToString();
}
}
I don’t get what the error is trying to say. I do this kinda stuff in C# Desktop apps all the time, I don’t understand how or what I’m doing wrong? Can someone please help?
Thank you!
You are not instantiating the class, so you would need to make it static.
More typically, though, you would have a
Userclass that you would create an instance of in your controller, and pass that to your model. This will help you avoid doing discreet queries for each piece of information you need.You may want to investigate the Repository Pattern.