简体   繁体   中英

C# error : An object reference is required for the non-static field

I've found many solutions on this but none of them make sense to me. Basically I'm submitting a form using jQuery AJAX and trying to update a row already in my table but get the error: An object reference is required for the non-static field. If I change the "txtContactLastEdit.Text;" to "New Name;" everything is fine. It's only when I refer to the txt field on the form. Any ideas? Thanks!

[WebMethod]
public static string updateProject(int id)
{
    using (dbPSREntities5 myEntities = new dbPSREntities5())
    {
        // Query for a specific customer. 
        var proj =
            (from tbProject in myEntities.tbProjects
             where tbProject.ProjectID == id
             select tbProject).First();

        // Change the name of the contact.
        proj.ProjectContactLastName = txtContactLastEdit.Text;

        // Ask the DataContext to save all the changes.
        myEntities.SaveChanges();

        var myResult = "success";

        return myResult;

    }
}

You can not access the page control inside the Static Method.

You probably calling this method from client side, So one alternative is that send the txtContactLastEdit.Text from the client side and change your function to accept that paramter.

[WebMethod]
public static string updateProject(int id, string textBoxValue)
{
  // your code.
}

Try to pass the value of the textbox to the static method

WebMethod]
public static string updateProject(int id, string contactName)
{
    ....

        // Change the name of the contact.
        proj.ProjectContactLastName = contatcName;


}

Inside a static method you cannot use instance variables of the class in which the static method id defined, and the txtContactLastEdit is an instance variable of the Page of type TextBox. So, supposing that the static method belongs to a class named Project, then you could call it from somewhere in your page.

int projectID = 1;
Project.updateProject(projectID,txtContactLastEdit.Text);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM