Introduction
In this post, How to implement Basic CRUD Functionality with the Entity Framework and ASP.NET MVC4 application.I have split the entire application split into following 3 parts for making things more simple and understandable specially for beginners.
- Part 1 : Perform read functionality of CRUD Operation.
- Part 2 : Perform create and update functionality of CRUD Operation.
- Part 3 : Perform delete functionality of CRUD Operation.
Steps :
Step-1: Write function for fetch countries from database.
Here I have written the below function "GetCountry" into "Contacts" Controller. private List<Country> GetCountry()
{
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
return dc.Countries.OrderBy(a => a.CountryName).ToList();
}
}
Step-2: Write function for fetch states from database.
Here I have written the below function "GetState" into "Contacts" Controller. private List<State> GetState(int countryID)
{
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
return dc.States.Where(a => a.CountryID.Equals(countryID)).OrderBy(a => a.StateName).ToList();
}
}
Step-3: Write function for return state list of selected country in json format, which we will use for cascade dropdown.
Here I have written the below function "GetStateList" into "Contacts" Controller. public JsonResult GetStateList(int countryID)
{
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
return new JsonResult { Data = GetState(countryID), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
Step-4: Write function for fetch contact data from database.
Here I have written the below function "GetContact" into "Contacts" Controller. public Contact GetContact(int contactID)
{
Contact contact = null;
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
var v = (from a in dc.Contacts
join b in dc.Countries on a.CountryID equals b.CountryID
join c in dc.States on a.StateID equals c.StateID
where a.ContactID.Equals(contactID)
select new
{
a,
b.CountryName,
c.StateName
}).FirstOrDefault();
if (v != null)
{
contact = v.a;
contact.CountryName = v.CountryName;
contact.StateName = v.StateName;
}
return contact;
}
}
Step-5: Add new action into your controller for get view for Save (Add and Edit) contact.
Here I have used "Save" Action. Please write this following code public ActionResult Save(int id = 0)
{
List<Country> country = GetCountry();
List<State> states = new List<State>();
if (id > 0)
{
//Update
var c = GetContact(id);
if (c != null)
{
ViewBag.Countries = new SelectList(country, "CountryID", "CountryName", c.CountryID);
ViewBag.States = new SelectList(GetState(c.CountryID), "StateID", "StateName", c.StateID);
}
else
{
return HttpNotFound();
}
return View(c);
}
else
{
//Create
ViewBag.Countries = new SelectList(country, "CountryID", "CountryName");
ViewBag.States = new SelectList(states, "StateID", "StateName");
return View();
}
}
Step-6: Add view for the Action & design.
Right Click on Action Method (here right click on the action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Add.[N:B:Please Rebuild solution before add view.]
Step-7: Add following jquery code in the view for cascade dropdown (country > state).
Please write this following code <script>
$(document).ready(function () {
$('#CountryID').change(function () {
var countryID = $(this).val();
var $state = $('#StateID');
$state.empty();
$state.append($('<option></option>').val('').html('Please Wait...'));
if (countryID =="") {
$state.empty();
$state.append($('<option></option>').val('').html('Select State'));
return;
}
$.ajax({
url: '/Contacts/GetStateList',
type: 'GET',
data: { 'countryID': countryID },
dataType: 'json',
success: function (d) {
$state.empty();
$state.append($('<option></option>').val('').html('Select State'));
$.each(d, function (i, val) {
$state.append($('<option></option>').val(val.StateID).html(val.StateName));
});
},
error: function () {
alert('Error');
}
});
});
});
</script>
Step-8: Add an another action for POST method for Save contact to the database.
Please write this following code [HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save(Contact c)
{
string message = "";
bool status = false;
//Save
if (ModelState.IsValid)
{
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
if (c.ContactID > 0)
{
//Update
var v = dc.Contacts.Where(a => a.ContactID.Equals(c.ContactID)).FirstOrDefault();
if (v != null)
{
v.ContactPerson = c.ContactPerson;
v.ContactNo = c.ContactNo;
v.CountryID = c.CountryID;
v.StateID = c.StateID;
}
else
{
return HttpNotFound();
}
}
else
{
//Add new
dc.Contacts.Add(c);
}
dc.SaveChanges();
status = true;
return RedirectToAction("Index");
}
}
else
{
message = "Error! Please try again.";
ViewBag.Countries = new SelectList(GetCountry(), "CountryID", "CountryName", c.CountryID);
ViewBag.States = new SelectList(GetState(c.CountryID), "StateID", "StateName", c.StateID);
}
ViewBag.Message = message;
ViewBag.Status = status;
return View(c);
}