удалить запись на клик, asp.net - PullRequest
0 голосов
/ 06 октября 2010

У меня есть форма, где пользователи могут подписаться и отписаться от моего списка рассылки.до сих пор у меня есть кнопка подписки, работающая нормально, функция «добавить участника».Теперь мне нужна помощь с моей функцией "удалить участника" (кнопка отписаться).это позволит пользователю удалить свою запись из базы данных.Когда я запускаю код и нажимаю кнопку «отписаться», я не могу понять правильную логику, чтобы он удалял запись пользователя, если она существует.Спасибо за вашу помощь!

вот код, который я использую для кнопок подписки и отписки -----------

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


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

        }

        protected void addMember(object sender, EventArgs e)
        {
            // here you are defining the classes for the database and the linq
            mailinglistClassDataContext Class = new mailinglistClassDataContext();
            mailinglistMember member = new mailinglistMember();

            // Now we are going to add the data to the member
           // Here we are going to let the system define a GUID for the unique user ID
            member.memberID = new Guid();

            // here we are going to capture the user inputs and we are going to set these to lower case especially the email so that we can do a proper comparison later.
            member.fname = txtFirstName.Text;
            member.lname = txtLastName.Text;
            member.email = txtEmail.Text;

            // Here we are going to create the URL so we can later remove the user if they decide to opt out. 
            member.removeurl = "http://removeuser.aspx?code=" + member.memberID.ToString();

            // Here we are going to use a LINQ query to search the class of mailinglistmembers for any emails that contain equal values of the text field and select it.
            var duplicatecheck = from emails in Class.mailinglistMembers
                                 where emails.email.Contains(txtEmail.Text)
                                 select emails;

            // Here we are going to check that the count of duplicate is equal to zero. If so then we are going to insert the member information into the class and then submit the changes to the database.
            if (duplicatecheck.Count() == 0)
            {
                Class.mailinglistMembers.InsertOnSubmit(member);
                Class.SubmitChanges();

            }
            else
            {
                lblDuplicate.Text = "Hey you have already entered your information.";
            }
        }


 protected void deleteMember(object sender, EventArgs e)
    {



        // here you are defining the classes for the database and the linq
        mailingListClassDataContext Class = new mailingListClassDataContext();
        mailinglistMember member = new mailinglistMember();



        // here we are going to capture the user inputs and we are going to set these to lower case especially the email so that we can do a proper comparison later.

        member.email = txtEmail.Text;


        // Here we are going to use a LINQ query to search the class of mailinglistmembers for any emails that contain equal values of the text field and select it.

                        var deleterec = from emails in Class.mailinglistMembers
                        where emails.email.Contains(txtEmail.Text) 
                             select emails;

        // Here we check if the record exisits

        if (deleterec.Count() == 0)
        {
            Class.mailinglistMembers.DeleteOnSubmit(member);
            Class.SubmitChanges();
            Response.Redirect("frm_confirmation.aspx");

        }
        else
        {
            lblDelete.Text = "No record exsists!";
        }
    }
}

Ответы [ 3 ]

0 голосов
/ 07 октября 2010

Попробуйте следующий код.

string mailAddress = txtEmail.Text.Trim().ToLower();

using (var db = new mailingListClassDataContext())
{
    var records = from e in db.mailinglistMembers
                  where e.mail == mailAddress
                  select e;

    if (records != null)
    {
        db.mailinglistMembers.DeleteAllOnSubmit(records);
        db.SubmitChanges();
        Response.Redirect("frm_confirmation.aspx");
        Response.End();
    }
    else
    {
        lblDelete.Text = "No records exists!";
    }
}
0 голосов
/ 11 января 2011

Похоже, кто-то пытался добавить код, который я изначально разместил в своей статье о проекте кода. Не уверен, что вы прочитали статью, но она может помочь решить вашу проблему и понять, как она должна была работать. Ссылка вернет вас на страницу удаления и захватит GUID. Я использовал GUID в качестве идентификатора для удаления пользователя. Оригинальный артикул

0 голосов
/ 06 октября 2010

Возможно, вы хотели это сделать:

                    var deleterec = Class.mailinglistMembers
                    .FirstOrDefault(emails => emails.email.Contains(txtEmail.Text));

    if (deleterec != null)
    {
        Class.mailinglistMembers.DeleteOnSubmit(deleterec);
        Class.SubmitChanges();
        Response.Redirect("frm_confirmation.aspx");

    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...