3

I am creating a web app, and within this app I want to allow users to update their user information (first name, last name, email, phone number, company name) or change their password. When the page loads, their current information is entered into the text boxes. My problem is that I don't know how to apply the changes the user makes. My code currently looks like this:

    DataClasses1DataContext context = new DataClasses1DataContext();
    User user = new User();


    protected void Page_Load(object sender, EventArgs e)
    {
        string usr = Session["SessionUserName"].ToString();

        user = (from u in context.Users
                    where u.username.Equals(usr)
                    select u).FirstOrDefault();

        txtFName.Text = user.firstName;
        txtLName.Text = user.lastName;
        txtCompany.Text = user.companyName;
        txtEmail.Text = user.email;
        txtPhone.Text = user.phoneNumber;


    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {

        using (DataClasses1DataContext context2 = new DataClasses1DataContext())
        {
            User nUser = (from u in context2.Users
                          where u.username == user.username
                          select u).SingleOrDefault();

            if (nUser != null)
            {
                //make the changes to the user
                nUser.firstName = txtFName.Text;
                nUser.lastName = txtLName.Text;
                nUser.email = txtEmail.Text;
                if (!String.IsNullOrEmpty(txtPhone.Text))
                    nUser.phoneNumber = txtPhone.Text;
                if (!String.IsNullOrEmpty(txtCompany.Text))
                    nUser.companyName = txtCompany.Text;
                nUser.timeStamp = DateTime.Now;
            }


            //submit the changes
            context2.SubmitChanges();

            Response.Redirect("Projects.aspx");

        }

This doesn't give me any errors, but it also doesn't apply the changes. Some google searching led me to add

context2.Users.Attach(nUser);

but that gave me the error message: System.InvalidOperationException: Cannot attach an entity that already exists. So I tried

context2.Users.Attach(nUser, true); 

and I got the same error message.

Looking at google some more I found information about detaching an entity first, but that information was about 3 years old and doesn't appear to be valid anymore (as context.Detach or context.Users.Detach are not options and give me build errors if I try to use them). Other error message I received (that I don't remember how I got to honestly) suggested that I change the update policy so I set all fields under the Users class to never for the update policy. There was suggestions to deserialize and then serialize the data again, but I couldn't find any information on how to do that. Any help would be appreciated.

EDIT: Changed the code due to some suggestions below, but it's still not working. I do not get any error messages, but the data is not being saved.

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string usr = Session["SessionUserName"].ToString();

            user = (from u in context.Users
                    where u.username.Equals(usr)
                    select u).FirstOrDefault();

            txtFName.Text = user.firstName;
            txtLName.Text = user.lastName;
            txtCompany.Text = user.companyName;
            txtEmail.Text = user.email;
            txtPhone.Text = user.phoneNumber;
        }  

    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {



                //make the changes to the user
                user.firstName = txtFName.Text;
                user.lastName = txtLName.Text;
                user.email = txtEmail.Text;
                if (!String.IsNullOrEmpty(txtPhone.Text))
                    user.phoneNumber = txtPhone.Text;
                if (!String.IsNullOrEmpty(txtCompany.Text))
                    user.companyName = txtCompany.Text;
                user.timeStamp = DateTime.Now;
                //submit the changes
            context.SubmitChanges();

            Response.Redirect("Projects.aspx");

      }
4

1 に答える 1

1

これは、更新前に同じ情報をそれらのテキストボックスに書き戻したために発生しています。page_load を次のように変更するだけです。

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string usr = Session["SessionUserName"].ToString();

        user = (from u in context.Users
                where u.username.Equals(usr)
                select u).FirstOrDefault();

        txtFName.Text = user.firstName;
        txtLName.Text = user.lastName;
        txtCompany.Text = user.companyName;
        txtEmail.Text = user.email;
        txtPhone.Text = user.phoneNumber;
    }
}

更新前に page_load が実行されています。したがって、元の値を再割り当てしてから、同じ値で更新しています。お役に立てれば!幸運を!

編集:質問が更新された後に行われた変更:

コード全体をこれに変更します。また、グローバル変数を処理する必要があることを確認する必要があることをいくつか追加し、トップからグローバル変数を削除しました。

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (Session["SessionUserName"] != null)
        {
            string usr = Session["SessionUserName"].ToString();

            DataClasses1DataContext context = new DataClasses1DataContext();
            User user = (from u in context.Users
                         where u.username.Equals(usr)
                         select u).FirstOrDefault();

            if (user != null)
            {
                txtFName.Text = user.firstName;
                txtLName.Text = user.lastName;
                txtCompany.Text = user.companyName;
                txtEmail.Text = user.email;
                txtPhone.Text = user.phoneNumber;
            }
            else
            {
                //--- handle user not found error
            }
        }
        else
        {
            //--- handle session is null
        }
    }
}

protected void btnUpdate_Click(object sender, EventArgs e)
{
    if (Session["SessionUserName"] != null)
    {
        string usr = Session["SessionUserName"].ToString();

        try
        {
            DataClasses1DataContext context = new DataClasses1DataContext();
            User nUser = (from u in context.Users
                          where u.username.Equals(usr)
                          select u).FirstOrDefault();

            //make the changes to the user
            nUser.firstName = txtFName.Text;
            nUser.lastName = txtLName.Text;
            nUser.email = txtEmail.Text;
            if (!String.IsNullOrEmpty(txtPhone.Text))
                nUser.phoneNumber = txtPhone.Text;
            if (!String.IsNullOrEmpty(txtCompany.Text))
                nUser.companyName = txtCompany.Text;
            nUser.timeStamp = DateTime.Now;

            //submit the changes
            context.SubmitChanges();

            Response.Redirect("Projects.aspx");
        }
        catch (Exception ex)
        {
            //--- handle update error
        }
    }
    else
    {
        //--- handle null session error
    }
}

それはあなたのためにうまくいくはずです。お知らせ下さい!幸運を!

于 2012-04-16T13:34:34.803 に答える