Crud operation in mvc with dbfirst and repository

 


Crud in MVC with DbFirst and Repository Pattern:-

C:-Create

R:-Read

U:-Update

D:-Delete

Repository Pattern:-  The repository patterns are intended to create an abstraction layer between the data access layer and the business logic layer of an application.






StudentController.cs

using System;

using System.Collections.Generic;

using System.Data;

using System.Data.Entity;

using System.Linq;

using System.Net;

using System.Web;

using System.Web.Mvc;

using DbFirstDemo.Repository;

using DbFirstDemo.Models;

 

namespace DbFirstDemo.Controllers

{

    public class StudentController : Controller

    {

        private StudentRepository _repository = new StudentRepository();

        

        public ActionResult Index()

        {

            var students=_repository.GetSudent();

            return View(students);

        } 

      

        public ActionResult Details(int? id)

        {

            if (id == null)

            {

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            }

 

            var student = _repository.GetStudentById(id);

 

            if (student == null)

            {

                return HttpNotFound();

            }

            return View(student);

        } 

       

        public ActionResult Create()

        {

            return View();

        }

        

        [HttpPost]

        [ValidateAntiForgeryToken]

        public ActionResult Create(Student student)

        {

            if (ModelState.IsValid)

            {

                _repository.AddStudent(student);

                return RedirectToAction("Index");

            } 

            return View(student);

        }

 

        // GET: Student/Edit/5

        public ActionResult Edit(int? id)

        {

            if (id == null)

            {

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            }

            var student = _repository.GetStudentById(id);

            if (student == null)

            {

                return HttpNotFound();

            }

            return View(student);

        }

 

 

        [HttpPost]

        [ValidateAntiForgeryToken]

        public ActionResult Edit(Student student)

        {

            if (ModelState.IsValid)

            {

                _repository.UpdateStudent(student);

                return RedirectToAction("Index");

            }

            return View(student);

        }

               

 

        public ActionResult Delete(int? id)

        {

          _repository.DeleteStudent(id);

            return RedirectToAction("Index");   

        }       

    }

}

 

StudentRepository.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using DbFirstDemo.Models;

 

namespace DbFirstDemo.Repository

{

    public class StudentRepository

    {

        public List<Student> GetSudent()

        {

            using (DbFirstProjectEntities _context=new DbFirstProjectEntities())

            {

                var students = _context.Students.ToList();

                return students;

            }            

        }

 

        public Student GetStudentById(int? id)

        {

            using (DbFirstProjectEntities _context = new DbFirstProjectEntities())

            {

                var student = _context.Students.Where(x=>x.Id==id).FirstOrDefault();

                return student;

            }

        }

 

        public void AddStudent(Student student)

        {

            using (DbFirstProjectEntities _context = new DbFirstProjectEntities())

            {

                 _context.Students.Add(student);

                 _context.SaveChanges();           

            }

        }

 

        public void UpdateStudent(Student student)

        {

            using (DbFirstProjectEntities _context=new DbFirstProjectEntities())

            {

                var studentInDb = _context.Students.Where(x=>x.Id==student.Id).FirstOrDefault();

                studentInDb.Name = student.Name;

                studentInDb.Age = student.Age;

                studentInDb.Gender = student.Gender;

                studentInDb.City = student.City;

                _context.SaveChanges();

            }

        }

 

        public void DeleteStudent(int? id)

        {

            using (DbFirstProjectEntities _context=new DbFirstProjectEntities())

            {

                var student = _context.Students.Find(id);

                _context.Students.Remove(student);

                _context.SaveChanges();              

            }

        }

    }

}


Views

1.Index.cshtml 

@model IEnumerable<DbFirstDemo.Models.Student>

 

@{

    ViewBag.Title = "Index";

}

 

<h2 style="text-align:center;color:red"><u>Student Details</u></h2>

 

<p>

    @Html.ActionLink("Create New", "Create","Student",new {@class="btn btn-success"})

</p>

<table class="table table-bordered table-striped table-condensed">

    <tr>

        <th>

            @Html.DisplayNameFor(model => model.Name)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.Age)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.Gender)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.City)

        </th>

        <th>Action</th>

    </tr>

 

@foreach (var item in Model) {

    <tr>

        <td>

            @Html.DisplayFor(modelItem => item.Name)

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.Age)

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.Gender)

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.City)

        </td>

        <td>

            @Html.ActionLink("Edit", "Edit","Student", new { id=item.Id},new { @class = "btn btn-primary" }) |

            @Html.ActionLink("Details", "Details", "Student", new { id=item.Id },new {@class = "btn btn-info" }) |

            @Html.ActionLink("Delete", "Delete", "Student", new { id=item.Id },new { @class = "btn btn-danger" })

        </td>

    </tr>

}

 

</table>

 

 

<style>

    table, tr, td, th {

        text-align:center

    }

</style>


2.Create.cshtml

@model DbFirstDemo.Models.Student 

@{

    ViewBag.Title = "Create";

 }

 

<h2>Create</h2> 

@using (Html.BeginForm())

{

    @Html.AntiForgeryToken()   

    <div class="form-horizontal">

        <h4>Student</h4>

        <hr />

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">

            @Html.LabelFor(model => model.Id, htmlAttributes: new { @class = "control-label col-md-2" })

            <div class="col-md-10">

                @Html.EditorFor(model => model.Id, new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.Id, "", new { @class = "text-danger" })

            </div>

        </div>

 

        <div class="form-group">

            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

            <div class="col-md-10">

                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

            </div>

        </div> 

        <div class="form-group">

            @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })

            <div class="col-md-10">

                @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })

            </div>

        </div>

 

        <div class="form-group">

            @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })

            <div class="col-md-10">

                @Html.EditorFor(model => model.Gender, new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })

            </div>

        </div>

 

        <div class="form-group">

            @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })

            <div class="col-md-10">

                @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })

            </div>

        </div>

 

        <div class="form-group">

            <div class="col-md-offset-2 col-md-10">

                <input type="submit" value="Create" class="btn btn-success"/>

            </div>

        </div>

    </div>

}

 

<div>

    @Html.ActionLink("Back to List", "Index")

</div>

 

@section Scripts {

    @Scripts.Render("~/bundles/jqueryval")

}


3.Edit.cshtml 

@model DbFirstDemo.Models.Student 

@{

    ViewBag.Title = "Edit";

}

 

<h2>Edit</h2>

 

@using (Html.BeginForm())

{

    @Html.AntiForgeryToken()

   

    <div class="form-horizontal">

        <h4>Student</h4>

        <hr />

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.HiddenFor(model => model.Id)

 

        <div class="form-group">

            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

            <div class="col-md-10">

                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

            </div>

        </div>

 

        <div class="form-group">

            @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })

            <div class="col-md-10">

                @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })

            </div>

        </div>

 

        <div class="form-group">

            @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })

            <div class="col-md-10">

                @Html.EditorFor(model => model.Gender, new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })

            </div>

        </div>

 

        <div class="form-group">

            @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })

            <div class="col-md-10">

                @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })

            </div>

        </div>

 

        <div class="form-group">

            <div class="col-md-offset-2 col-md-10">

                <input type="submit" value="Save" class="btn btn-default" />

            </div>

        </div>

    </div>

}

 

<div>

    @Html.ActionLink("Back to List", "Index")

</div>

 

@section Scripts {

    @Scripts.Render("~/bundles/jqueryval")

}


4.Details.cshtml 

@model DbFirstDemo.Models.Student 

@{

    ViewBag.Title = "Details";

}

 

<h2>Details</h2> 

<div>

    <h4>Student</h4>

    <hr />

    <dl class="dl-horizontal">

        <dt>

            @Html.DisplayNameFor(model => model.Name)

        </dt> 

        <dd>

            @Html.DisplayFor(model => model.Name)

        </dd>

 

        <dt>

            @Html.DisplayNameFor(model => model.Age)

        </dt>

 

        <dd>

            @Html.DisplayFor(model => model.Age)

        </dd>

 

        <dt>

            @Html.DisplayNameFor(model => model.Gender)

        </dt>

 

        <dd>

            @Html.DisplayFor(model => model.Gender)

        </dd> 

        <dt>

            @Html.DisplayNameFor(model => model.City)

        </dt> 

        <dd>

            @Html.DisplayFor(model => model.City)

        </dd>

 

    </dl>

</div>

<p>

    @Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |

    @Html.ActionLink("Back to List", "Index")

</p>


5.Delete.cshtml 

@model DbFirstDemo.Models.Student 

@{

    ViewBag.Title = "Delete";

}

 

<h2>Delete</h2>

 

<h3>Are you sure you want to delete this?</h3>

<div>

    <h4>Student</h4>

    <hr />

    <dl class="dl-horizontal">

        <dt>

            @Html.DisplayNameFor(model => model.Name)

        </dt>

 

        <dd>

            @Html.DisplayFor(model => model.Name)

        </dd> 

        <dt>

            @Html.DisplayNameFor(model => model.Age)

        </dt>

 

        <dd>

            @Html.DisplayFor(model => model.Age)

        </dd>

 

        <dt>

            @Html.DisplayNameFor(model => model.City)

        </dt>

 

        <dd>

            @Html.DisplayFor(model => model.City)

        </dd>

 

    </dl>

 

    @using (Html.BeginForm()) {

        @Html.AntiForgeryToken()

 

        <div class="form-actions no-color">

            <input type="submit" value="Delete" class="btn btn-default" /> |

            @Html.ActionLink("Back to List", "Index")

        </div>

    }

</div>

 


No comments:

Post a Comment