65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP.NET MVC 4 使用 XML 数据进行 CRUD 操作 Web 应用程序

starIconstarIconstarIconstarIconstarIcon

5.00/5 (5投票s)

2015 年 1 月 27 日

CPOL

3分钟阅读

viewsIcon

50037

downloadIcon

1223

在 ASP.NET MVC 中,创建、读取、更新、删除、登录和登出 (CRUD) 操作很容易执行。通过使用默认的 T4 自动生成模板和强类型视图,您可以快速构建一个能够创建、更新和删除记录的 Web 应用程序。

创建学生详细信息:- 逐步指南

创建 MVC4 Web 应用程序

 

选择“新建项目”

选择“Web 应用程序”,MVC 4,如下图所示

选择“基本应用程序”

点击“确定”按钮后,项目将创建完成。

首先,为应用程序创建一个空的控制器,如下所示:

步骤 1:- 现在需要在 App 文件夹中添加 XML 数据文件,如下图所示:

选择 XML 文件,然后按如下方式添加该文件,

我使用 ASP.NET MVC 4 构建了一个简单的计费应用程序,该应用程序对 XML 文件执行 CRUD 操作。通过 LINQ,我能够快速编写代码来更新 XML 文件中的节点。

仅选择 XML 文件。

创建注册表单所需的属性,如下所示:

我的应用程序如何工作

我的 ASP.NET MVC 4 计费应用程序使用 存储库模式 来访问数据。此模式的优点是它使我的方法更易于维护,并限制了数据访问层中的重复代码量。对于每个 CRUD 操作,我的存储库中都有一个相应的方法。

现在需要为模型值添加模型类,如下所示:

并按如下方式选择:

 

 

此代码用于 StudentRepository 获取数据

所有繁重的工作都由我的 StudentRepository.cs 类完成。

        private List<StudentsModel> allStudents;
        private XDocument StudentsData;

        public StudentRepository()
        {
            try
            {
                allStudents = new List<StudentsModel>();
                StudentsData = XDocument.Load(HttpContext.Current.Server.MapPath("~/App_Data/StudentData.xml"));
                var Students = from t in StudentsData.Descendants("item")
                               select new StudentsModel(
                                   (int)t.Element("id"),
                                   t.Element("first_name").Value,
                               t.Element("last_name").Value,
                               t.Element("email_id").Value,
                               t.Element("password").Value,
                               t.Element("upload_img").Value,
                               (DateTime)t.Element("dob"),
                               t.Element("gender").Value,
                               t.Element("cell_number").Value,
                               t.Element("college").Value,
                               t.Element("adress").Value,
                               t.Element("city").Value,
                               t.Element("state").Value,
                               t.Element("pin").Value);

                allStudents.AddRange(Students.ToList<StudentsModel>());
            }
            catch (Exception)
            {

                throw new NotImplementedException();
            }
        }

        public IEnumerable<StudentsModel> GetStudents()
        {
            return allStudents;
        }

       

        public StudentsModel GetStudentByEmailPwd(string email, string pwd)
        {
            return allStudents.Find(t => t.Email_id == email && t.Password == pwd);
        }

        public StudentsModel GetStudentByID(int id)
        {
            return allStudents.Find(item => item.ID == id);            
        }

        public void InsertStudentsModel(StudentsModel Student)
        {
            Student.ID = (int)(from S in StudentsData.Descendants("item") orderby (int)S.Element("id") descending select (int)S.Element("id")).FirstOrDefault() + 1;

            StudentsData.Root.Add(new XElement("item", new XElement("id", Student.ID),
                new XElement("first_name", Student.First_Name),
                new XElement("last_name", Student.Last_Name),
                new XElement("email_id", Student.Email_id),
                new XElement("password", Student.Password),
                new XElement("upload_img", Student.Upload_img),
                new XElement("dob", Student.Dob.Date.ToShortDateString()),
                new XElement("gender", Student.Gender),
                new XElement("cell_number", Student.Cell_number),
                new XElement("college", Student.College),
                new XElement("adress", Student.Adress),
                new XElement("city", Student.City),
                new XElement("state", Student.State),
                new XElement("pin", Student.Pin)));

            StudentsData.Save(HttpContext.Current.Server.MapPath("~/App_Data/StudentData.xml"));
        }       

        public void EditStudentsModel(StudentsModel Student)
        {
            try
            {
                XElement node = StudentsData.Root.Elements("item").Where(i => (int)i.Element("id") == Student.ID).FirstOrDefault();

                node.SetElementValue("first_name", Student.First_Name);
                node.SetElementValue("last_name", Student.Last_Name);
                //node.SetElementValue("email_id", Student.Email_id);
                //node.SetElementValue("password", Student.Password);
                //node.SetElementValue("upload_img", Student.Upload_img);
                node.SetElementValue("dob", Student.Dob.ToShortDateString());
                node.SetElementValue("gender", Student.Gender);
                node.SetElementValue("cell_number", Student.Cell_number);
                node.SetElementValue("college", Student.College);
                node.SetElementValue("adress", Student.Adress);
                node.SetElementValue("city", Student.City);
                node.SetElementValue("state", Student.State);
                node.SetElementValue("pin", Student.Pin);
                StudentsData.Save(HttpContext.Current.Server.MapPath("~/App_Data/StudentData.xml"));
            }
            catch (Exception)
            {

                throw new NotImplementedException();
            }
        }

        public void DeleteStudentsModel(int id)
        {
            try
            {
                StudentsData.Root.Elements("item").Where(i => (int)i.Element("id") == id).Remove();

                StudentsData.Save(HttpContext.Current.Server.MapPath("~/App_Data/StudentData.xml"));

            }
            catch (Exception)
            {

                throw new NotImplementedException();
            }
        }       
   

 

现在,在模型中添加接口类以实现方法,如下所示:

 

 

public interface IStudentRepository

我的模型文件夹还包含我的接口 IStudentRepository.cs

IEnumerable<StudentsModel> GetStudents();
        List<string> Getemail();
        StudentsModel GetStudentByID(int id);
        StudentsModel GetStudentByEmailPwd(string email, string pwd);
        void InsertStudentsModel(StudentsModel Student);
        void DeleteStudentsModel(int id);
        void EditStudentsModel(StudentsModel Student);

 

 

StudentModel 属性类

在我的 StudentModel.cs 类中,我使用了 System.ComponentModel.DataAnnotations 命名空间为我的模型属性添加验证。

 public StudentsModel()
        {            
            this.ID = 0;
            this.First_Name = null;
            this.Last_Name = null;
            this.Email_id = null;
            this.Password = null;
            this.Upload_img = null;
            this.Dob = DateTime.Now;
            this.Gender = null;
            this.Cell_number = null;
            this.College = null;
            this.Adress = null;
            this.City = null;
            this.State = null;
            this.Pin = null;
        }
        public StudentsModel(int id, string first_Name, string last_Name, string email_id,string password, string upload_img, DateTime dob, string gender, string cell_number, String college,string adress, string city, string state, string pin)
        {
            this.ID = id;
            this.First_Name = first_Name;
            this.Last_Name = last_Name;
            this.Email_id = email_id;
            this.Password = password;
            this.Upload_img = upload_img;
            this.Dob = dob;
            this.Gender = gender;
            this.Cell_number = cell_number;
            this.College = college;
            this.Adress = adress;
            this.City = city;
            this.State = state;
            this.Pin = pin;

        }
        public StudentsModel(string email_id, string pwd)
        {
            this.Email_id = email_id;
            this.Password = pwd;
        }
       
        
        public int ID { get; set; }
        [Required(ErrorMessage = "First name is required")]
        public string First_Name { get; set; }
        [Required(ErrorMessage = "First name is required")]
        public string Last_Name { get; set; }
        [Required(ErrorMessage = "Email name is required")]
        [DataType(DataType.EmailAddress)]
        public string Email_id { get; set; }
        [Required(ErrorMessage = "Password is required")]
        public string Password { get; set; }
        [Required(ErrorMessage = "Profile pic is required")]
        [DataType(DataType.Upload)]
        public string Upload_img { get; set; }
        [Required(ErrorMessage = "Date of birth is required")]
        [DisplayFormat(DataFormatString = "{0:d MMM yyyy}")]
        public DateTime Dob { get; set; }
        [Required(ErrorMessage = "Plaese select required")]
        public string Gender { get; set; }
        [Required(ErrorMessage = "CellNo is required")]
        [DataType(DataType.PhoneNumber)]
        public string Cell_number { get; set; }
        [Required(ErrorMessage = "College name is required")]
        public string College { get; set; }
        [Required(ErrorMessage = "Student adress is required")]
        public string Adress { get; set; }
        [Required(ErrorMessage = "Your city is required")]
        public string City { get; set; }
        [Required(ErrorMessage = "Your sate is required")]
        public string State { get; set; }
        [Required(ErrorMessage = "Postal code is required")]
        [DataType(DataType.PostalCode)]
        public string Pin { get; set; }

控制器 (Controller)

我有一个名为 HomeController.cs 的控制器,它与我的存储库交互,并包含用于执行 CRUD 操作的 get 和 post 请求。通过使用 ModelState.AddModelError() 方法,我能够在任何失败的 CRUD 操作中以红色字体显示异常错误消息。

现在是时候创建注册、更新、删除、登录首页、登出表单了,

1.如何创建注册表单

 

在您的控制器中添加 `CreateRegistration` 控制器方法,并附带如下图所示的上传图片代码。

#region Creating student registration
        /// <summary>
        /// CreatStudentRegistartion
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CreatStudentRegistartion()
        {
            return View();
        }

        [HttpPost]
        public ActionResult CreatStudentRegistartion(StudentsModel students, HttpPostedFileBase file)
        {
            try
            {
                string ImageName = ""; if (file != null)
                {
                    ImageName = Path.GetFileName(file.FileName);
                    var physicalPath = Path.Combine(Server.MapPath("~/StudentImg"), students.Email_id + ImageName);
                    students.Upload_img = students.Email_id + ImageName;
                    _StudentsRepository.InsertStudentsModel(students);
                    file.SaveAs(physicalPath);
                }
                TempData["mySesstion0"] = students.Email_id; TempData["mySesstion1"] = students.Password;
                return RedirectToAction("../Home/Index");
            }
            catch (Exception)
            {
                throw new NotImplementedException();
            }
        }
        #endregion




 

为控制器添加强类型视图,遵循以下步骤:

next

按如下方式选择:创建、编辑、删除,与下面相同

 

2.如何更新注册

在您的控制器中添加 `UpdateRegistration` 控制器方法,并附带如下图所示的不含上传图片的代码。

#region Update student registration
        /// <summary>
        /// CreatStudentRegistartion
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult UpdateStudentRegistartion(int studentID)
        {
            try
            {
                return View(_StudentsRepository.GetStudents().Where(s => s.ID == studentID).ToList());
            }
            catch (Exception)
            {
                throw;
            }
        }
        [HttpPost]
        public ActionResult UpdateStudentRegistartion(StudentsModel students, HttpPostedFileBase file)
        {
            try
            {
                _StudentsRepository.EditStudentsModel(students);
                TempData["Sucss"] = "You are record update successfully..";
                TempData["mySesstion0"] = students.Email_id; TempData["mySesstion1"] = students.Password;
                return RedirectToAction("../Home/Index");
            }
            catch (Exception)
            {
                throw new NotImplementedException();
            }
        }
        #endregion

 

3.如何删除注册

在您的控制器中添加 `DeleteRegistration` 控制器方法,并附带如下图所示的代码。

 

#region Delete Selected Student Records
        /// <summary>
        /// Delete
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Delete(int id)
        {
            StudentsModel AllStudents = _StudentsRepository.GetStudentByID(id);
            if (AllStudents == null)
                return RedirectToAction("Index");
            return View(AllStudents);
        }

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                _StudentsRepository.DeleteStudentsModel(id);
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        #endregion

 

4.如何创建登录页并通过匹配的电子邮件和密码获取学生信息

 

此处使用 sessions 和 temp data 来存储登录用户的数据到 session 中。

 

#region Login success are fails
        /// <summary>
        /// index
        /// </summary>
        /// <param name="Email_id"></param>
        /// <param name="Password"></param>
        /// <returns></returns>
        public ActionResult Index(string Email_id, string Password)
        {
            try
            {
                List<StudentsModel> AllStudents = new List<StudentsModel>();

                if (TempData["mySesstion0"] != null)
                {
                    Email_id = TempData["mySesstion0"].ToString(); Password = TempData["mySesstion1"].ToString();
                }
                if (Email_id != null && Password != null)
                {
                    AllStudents = _StudentsRepository.GetStudents().Where(s => s.Email_id == Email_id && s.Password == Password).ToList();
                    if (AllStudents.Count != 0)
                    {
                        Session["UserData"] = AllStudents;
                        TempData["Email"] = AllStudents[0].Email_id;
                        TempData["Pwd"] = AllStudents[0].Password;
                        TempData["MyID"] = AllStudents[0].ID;
                        return View(AllStudents);
                    }
                    else
                    {
                        TempData["ErrorLogin"] = "username or password you entered is incorrect...";
                        return View("../Home/LoginPage");
                    }
                }
                else
                {
                    return View("../Home/LoginPage");
                }
            }
            catch (Exception)
            {

                throw new NotImplementedException();
            }

        }
        #endregion

 

 

5.登出

这可用于移除 session 中存储的数据。

 

#region session Log off controlle
        /// <summary>
        /// log - off session  
        /// </summary>
        /// <returns></returns>
        public ActionResult Signout()
        {
            Session.Clear();
            Session.Abandon();
            return RedirectToAction("Index");
        }
        #endregion

输出屏幕

1.登录屏幕

2.注册屏幕(带模型验证)

 

3.注册成功后

 

 

4.更新屏幕

 

 

 

© . All rights reserved.