简体   繁体   中英

Error 4 A namespace cannot directly contain members such as fields or methods

I am supposed to do a project in class where I have to setup a website from scratch using C# and ASP.NET.

My objective is to create a contact form in this case where the function is to send an email to the designated address upon the clicking of a button where I've tried to create by Googling the codes. However, I've encountered the error , "A namespace cannot directly contain members such as fields or methods. "

Could anyone help? Thanks in advance!

The codes that I've used on the page are as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

<%@Import Namespace="System.Web.Mail" %>;
<script language="c#" runat="server">;



public partial class ContactUs : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }


    protected void Button1_Click(object sender, EventArgs e)
    {

        MailMessage msg = new MailMessage();

        msg.To = "sarahhhhh@gmail.com";
        msg.From = nameTB.text;
        msg.Subject = subjectTB.text;
        msg.Body = messageTB.text;
        lblStatus.Text = "Sending...";

        SmtpMail.Send(msg);
        lblStatus.Text = "Sent email (" + txtSubject.Text + ") to " + txtTo.Text;
    }
}

Remove these lines:-

<%@Import Namespace="System.Web.Mail" %>;
<script language="c#" runat="server">;
</script> //If it's present

And add using System.Web.Mail; at the top like other namespaces are included. Your this file with aspx.cs file extension is called Code Behind file, You should read the basics first. Refer this .

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