Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to delete a record in MVC 5 web application using repository pattern and have a business logic layer
Posted

1 solution

//In your Business Logic layer write this code following code

//Getting a record by Id first
public PatientDataModel GetById(string id)
{

using (var patientRep = new PatientRepository())
{


PatientDataModel patient = patientRep.GetById(id);
var pat = new PatientViewModel();

if (patient != null)
{
pat.IdNo = patient.IdNo;
pat.FirstName = patient.FirstName;
pat.LastName = patient.LastName;
pat.Gender = patient.Gender;
pat.Email = patient.Email;
pat.CellPhoneNo = patient.CellPhoneNo;
pat.Address = patient.Address;
}
return patient;
}
}

C#
public void Delete(PatientViewModel model)
        {
            using (var patientRep = new PatientRepository())
            {
                var patient = new PatientDataModel();
                patient = patientRep.GetById(model.IdNo);
                if (patient != null)
                {

                    patientRep.Delete(patient);

                }
            }

        }


//Then in your controller write this code

[HttpGet]
public ActionResult Delete(string id)
{
var patientb = new PatientBusiness().GetById((id));
return View(patientb);
}
[HttpPost]
public ActionResult Delete(PatientViewModel model)
{
var patientb = new PatientBusiness();
try
{
if (ModelState.IsValid)
{
patientb.Delete(model);

return RedirectToAction("Index");
}
}
catch (Exception)
{

ModelState.AddModelError("", "Unable to Edit your profile.Try again, and if the problem persists see your system administrator.");
}
return RedirectToAction("Index");
}

//Then create a view

@model DutClinicData.PatientDataModel

@{
ViewBag.Title = "Delete";
Layout = "~/Views/Shared/_Layout.cshtml";
}

Delete



Are you sure you want to delete this?



PatientDataModel






@Html.DisplayNameFor(model => model.FirstName)
@Html.DisplayFor(model => model.FirstName)
@Html.DisplayNameFor(model => model.LastName)
@Html.DisplayFor(model => model.LastName)
@Html.DisplayNameFor(model => model.Gender)
@Html.DisplayFor(model => model.Gender)
@Html.DisplayNameFor(model => model.CellPhoneNo)
@Html.DisplayFor(model => model.CellPhoneNo)
@Html.DisplayNameFor(model => model.Address)
@Html.DisplayFor(model => model.Address)
@Html.DisplayNameFor(model => model.Email)
@Html.DisplayFor(model => model.Email)


@using (Html.BeginForm()) {
@Html.AntiForgeryToken()


<input type="submit" value="Delete" class="btn btn-default" /> |
@Html.ActionLink("Back to List", "Index")

}


//Anyone can improve this answer
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900