开发者

CS0120: An object reference is required

开发者 https://www.devze.com 2023-01-07 20:09 出处:网络
Getting this error when I submit my form to savetext.aspx action file: Compiler Error Message: CS0120: An object reference is required for the nonstatic field, method, or property \'System.Web.UI.Pag

Getting this error when I submit my form to savetext.aspx action file:

Compiler Error Message: CS0120: An object reference is required for the nonstatic field, method, or property 'System.Web.UI.Page.Request.get'

On this line:

string path = "/txtfiles/" + Request.Form["file_name"];

Whole code:

<%@ Page Language="C#" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>

<script runat="server">

class Test 
{
    public static void Main() 
    {
        string path = "/txtfiles/" + Request.Form["file_name"];
        if (!File.Exists(path)) 
        {
            using (StreamWriter sw = File.CreateText(path)) 
      开发者_StackOverflow      {
                sw.WriteLine(request.form["seatsArray"]);
            sw.WriteLine("");
            }   
        }

        using (StreamReader sr = File.OpenText(path)) 
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) 
            {
                Console.WriteLine(s);
            }
        }
    }
}
</script>

How do I fix it?

Thanks!


Remove this Test class as well as the static Main method and replace it with a Page_Load instance method like so:

<%@ Page Language="C#" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>

<script runat="server">
    protected void Page_Load(object sender, EventArgs e) 
    {
        string path = "/txtfiles/" + Request.Form["file_name"];
        if (!File.Exists(path)) 
        {
            using (StreamWriter sw = File.CreateText(path)) 
            {
                sw.WriteLine(Request.Form["seatsArray"]);
                sw.WriteLine("");
            }   
        }

        using (StreamReader sr = File.OpenText(path)) 
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) 
            {
                Response.Write(s);
            }
        }
    }
</script>

Also you probably want to output to the HttpResponse instead of a console in a web application. Another remark is about your file path: "/txtfiles/", NTFS usually doesn't like such patterns.


Darin Dimitrov gave you a hint in right direction, but i want just to give answer to question why does this error happen. Normal error should be:

The name 'Request' does not exist in the current context

This happen because for each aspx file a class is created that inherits from Page by default. All new classes defined inside aspx file become nested classes of that one. Request is member of class Page and this particular error happen because you try to access it from static method of nested type.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号