Create Student details: - step by step
Create MVC4 web application
Select new project
Select web application, MVC 4, above image
Select basic application
When click ok button project will be created.
First create the controller for application with empty controller like this
Step 1: Now need to add xml data file App folder look image below
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.
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.
Now need to add model class for model values like given bellow
And select like this
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("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();
}
}
Colourised in 65ms
Now add the interface class in model for method implementation like given bellow
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);Colourised in 4ms
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; }
Colourised in 56ms
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
[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();
}
}
#endregionColourised in 22ms
Add View for controller to strong type follow steps
next
select like this create , edit, delete, same given below
2.How to update registration
In your controller add Updategistration controller method with out upload image code given below.
#region Update student registration
[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();
}
}
#endregionColourised in 23ms
3.How to delete registration
In your controller add Deletegistration controller method code given below.
#region Delete Selected Student Records
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;
}
}
#endregionColourised in 17ms
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
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();
}
}
#endregionColourised in 37ms
5.Log out
This can be use to session stored data removing
#region session Log off controlle
public ActionResult Signout()
{
Session.Clear();
Session.Abandon();
return RedirectToAction("Index");
}
#endregionColourised in 10ms
Output Screens
1.Login Screen
2.Regisrtation Screen with model vaidations
3.Registration Success ofter
4.Update Screen