Click here to Skip to main content
15,507,388 members
Articles / Web Development / HTML
Article
Posted 27 Jan 2015

Stats

43.8K views
1.1K downloads
10 bookmarked

CRUD Operations Web Application/ XML Data in ASP.NET MVC 4

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
27 Jan 2015CPOL3 min read
Create, read, update, delete,Log in and Log out, (CRUD) operations are easy to perform in ASP.NET MVC. By using the default T4 scaffolding templates and strongly-typed views you can quickly build a web application that can create, update, and delete records.

Create Student details: - step by step

Create MVC4 web application

Image 1

 

Select new project

Image 2

Select web application, MVC 4, above image

Image 3

Select basic application

Image 4

When click ok button project will be created.

First create the controller for application with empty controller like this

Image 5

Step 1: Now need to add xml data file App folder look image below

Image 6

Select the xml file and add that select file like given below,

Using ASP.NET MVC 4 I built a simple Billing Application that performs CRUD operations on an XML file. With LINQ I was able to quickly write code to update nodes in the XML file.

Image 7

Select only XML file.

Create registration form required properties like given below,

How my app works

My ASP.NET MVC 4 Billing App uses the Repository pattern for accessing data. The advantages with this pattern are it makes my methods easier to maintain and limits the amount of duplicated code in the data access layer. For each CRUD operation I have a method in my repository.

Image 8

Now need to add model class for model values like given bellow

Image 9

And select like this

Image 10

 

 

This code use for studen StudentRepository Get Data

And all the heavy lifting is done by my StudentRepository.cs class.

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();
    }
}

 

Now add the interface class in model for method implementation like given bellow

 

Image 12

 

public interface IStudentRepository

My model folder also contains my interface 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 Properties class

In my StudentModel.cs class I used the System.ComponentModel.DataAnnotations namespace for adding validation to my model properties.

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

I have one Controller named HomeController.cs which interacts with my repository and contains get and post requests for performing CRUD operations. By using the ModelState.AddModelError() method I am able to display Exception error messages in red font for any failed CRUD operations.

Now time to create registration ,update,delete ,login index,log out form,

1.How to  create registration form

 

In your controller add createregistration controller method with upload image code given below.

#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

 

Add View for controller to strong type follow steps

Image 16

next

select like this create , edit, delete, same given below

Image 17

 

2.How to update registration

In your controller add Updategistration controller method with out upload image code given below.

#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.How to delete registration

In your controller add Deletegistration controller method  code given below.

 

#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.How to create login from Index  and  Get The Matched Student Emaild and Password

 

There is used sessions and temp data to store the loge user data in 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.Log out

This can be use to session stored data removing

 

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

Output Screens

1.Login Screen

Image 22

2.Regisrtation Screen with model vaidations

 

Image 23

3.Registration Success ofter

 

Image 24

 

4.Update Screen

 

Image 25

 

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionMultiple XML element Pin
Member 985359214-Mar-17 7:03
Member 985359214-Mar-17 7:03 
QuestionNice Post Pin
islam_ashraful6-Sep-15 22:09
islam_ashraful6-Sep-15 22:09 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun27-Jan-15 22:34
Humayun Kabir Mamun27-Jan-15 22:34 
GeneralRe: My vote of 5 Pin
luckylaxman28-Jan-15 19:40
professionalluckylaxman28-Jan-15 19:40 
GeneralMy vote of 5 Pin
Volynsky Alex27-Jan-15 11:38
professionalVolynsky Alex27-Jan-15 11:38 
GeneralRe: My vote of 5 Pin
luckylaxman28-Jan-15 19:38
professionalluckylaxman28-Jan-15 19:38 
GeneralRe: My vote of 5 Pin
Volynsky Alex29-Jan-15 8:45
professionalVolynsky Alex29-Jan-15 8:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.