Introduction
Hi Guys, Hope you have undergone the previous article where we learn how to start with MVC and what are prerequisites. This is continue to the article "Start With MVC - Push Start For Beginners(Part - 1)". As i promised, here you will learn about Viewing saved records, Edit Records using MVC with Entity To Sql. So Let's start.
Background
If you have undergone the part-1 of this series, you are ready for this article else please go through the part 1. Although you can start from this article too if you are already known to MVC, still i suggest you to read the previous article at one. So lets start the "Updating In MVC" . All the best !!
Using the code
1. View Saved Records (Listed View)
Till now we have learn how to add the new record to the list. Now lets start how can we see the records we added. This section is critical as we have to display the saved records several time. So here you will see a simple approach to display records in the list(tabular) form, although you can customize you view as you want. Its very simple.
1. Adding the Action method In Controller
Now, first of all we have to add a Action
which will return us the view for listed data.Below is the snapshot of the controller code. We have added this action (method) in the same controller i.e. "FirstController
" in which we are working in part - 1.
Note: To check how to add Views
or Controllers
please visit the previous article(step 5 and Step 6).
public ActionResult ViewAllRecords()
{
StartWithMVCEntities db = new StartWithMVCEntities();
List<Employee> empList = db.Employees.ToList();
return View(empList);
}
So, here you might have got idea the in MVC we have the same controller but it can render or serve user multiple View by using multiple Models.
Now Lets analyse our code, in line one have established the entity object connection to database and fetched all the records and passed this as a "List" object of type List<Employee>
to the view.
Now we need a view where we can display the record contained in this enumerable object. So next is adding appropriate view.
2. Adding View and Its Content
Now follow the steps to add the View to this method(Action method). Below is the Razor Code(HTML) for that.
@model List<StartWithMVC.Models.Employee>
@{
ViewBag.Title = "ViewAllRecords";
}
<h2>View Records</h2>
<div class="table_container">
<table>
<thead>
<th>HR Emp Id</th>
<th>Last Name</th>
<th>First Name</th>
<th>City</th>
<td>Edit</td>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.HREmpId</td>
<td>@item.LastName</td>
<td>@item.FirstName</td>
<td>@item.City</td>
<td>@Html.ActionLink("Edit", "EditRecord", new { recordID = @item.EmpId })</td>
</tr>
}
</tbody>
</div>
Now we have keep one this in mind that the object we are passing to this model is of list type "List
" so we have added "List<StartWithMVC.Models.Employee>" to the beginning of the view. Doing this will make us able to loop through the every record of the model object passed.
Note: You can use any of enumerable object (IDictionary, IEnumerable...etc) for this purpose but the List is simplest and easiest.
Here is snapshot explaining in details about what any syntax means in this part of code.
Here you will see i have used 'foreach
' loop for every item in out Model. Now "@item
" object is strongly type showing us the help intellisesne for every property we added. So this will decrease the chances of mistake as strongly type objects are verified at compile time. So error fixing is quite easy or we can say they are error proof in most of the cases.
Now its time to build the project to check out efforts.
3. Build And Run The Project
Now we are ready with our show records view. Just run the project and you will see the listed view of all added records. Here is the screen shot of how it will be.
This is it. Isn't it quite easy !! Now, just give it a try on your own. All the best.
Note: Here i have added some "Style" to make this view looks like that. You can just have this css added in your view too.Here it is. Just paste the block anywhere in the view.
<style type="text/css">
table td, th
{
border:1px solid black;
padding:2px;
}
div.table_container
{
float:left;
width:100%;
}
</style>
But its always suggested to write the style sheet for you styles and include that in bundle register. For any help on bundle registry, post your query.
2. Edit Saved Records
1. Write Action for Edit record
If you have noticed that i have added an action link in the above 'cshtml' with 'EditRecords
' method reference. Till now if you run the project and click on 'Edit' link, it will display Error. This is because the 'controller will searched for 'EditRecords' action method but it doesn't exists yet. So it throws the error.
Now we will see how we can edit record using the 'EditRecords' action. Here is the code for edit records method.
public ActionResult EditRecord(int recordID)
{
StartWithMVCEntities db = new StartWithMVCEntities();
Employee objEmp = db.Employees.ToList().Find(m => m.EmpId == recordID);
return View("Index", objEmp);
}
Now in above method the things you noticed are
1. Parameter 'recordID' : This is actually the parameter received from the edit action link click. Now when when you hover your mouse over edit link in the view of listed view, you will see the url like
http:
Here is the details of what it means as per code written above:
/First -- > refer to the FirstController, So it will look into this controller
/EditRecord -- > refer to 'EditRecord' method into our 'FirstController'
?recordID=2 -- > refer that it will search a method that accept the parameter called 'recordID' and '2' will passed as parameter value.
2. Linq Expression: Here we are fetching the employee object for the record that has EmpID
equals to recordID pass. Its pure Linq to Entity object.
2. Return : Here you ca,n see that we have returned the 'Index
' view with the object of the employee record. Now you did we use 'Index; view here ??
Answer: To edit records we need the edit fields for each of the column in the tale. For that we have two options.
1. Add new view
2.Re-use the view used to add new record.
So choice is yours what you want. But it is always preferred to have minimum view and controllers as possible. Also, we know that our 'Index
' view is of 'Employe
e' type. So i sued that save. Now It will display the values in the fields as contained by the 'objEmp
' object. So
And we can our edit record fulfill the requirements for this rout. Now here is snapshot of it to get better explanation
2. Build And Run Project
Now we are done with writing the edit record code. Now just run the project .
Now just go to the view records page and click on edit link. You will be redirected to the Index view with fields having the values for the records we wanted to edit. Here is the screenshot.
So we are on the same view where we added the new record, but here when you click on submit, it will update the record instead of adding new record. How we handle this in controller is next.
3. Method for Updating the record
If you have remembered that we have written the method to add a new record for 'click' event of the submit button using form post method. Here also we will do the same by modifying our existing method of add new record i.e. 'SaveEmployee
'
Here is new method
public ActionResult SaveEmployee(Employee objEmployee)
{
StartWithMVCEntities db = new StartWithMVCEntities();
if (objEmployee != null && objEmployee.EmpId != 0)
{
Employee objEmp = db.Employees.ToList().Find(m => m.EmpId == objEmployee.EmpId);
objEmp.HREmpId = objEmployee.HREmpId;
objEmp.FirstName = objEmployee.FirstName;
objEmp.LastName = objEmployee.LastName;
objEmp.Address = objEmployee.Address;
objEmp.City = objEmployee.City;
db.SaveChanges();
}
else
{
db.Employees.AddObject(objEmployee);
db.SaveChanges();
}
return RedirectToAction("ViewAllRecords");
}
Changes to be notices:
As we have passed the employee record object record to the view so, the value of EmpID (Primary Key) is non zero for edit case. So i have added the check for update and save on the basis of EmpID.
Now If are landed on Index page from 'EditRecords' action , the value of EmpID is always non-zero and thus let the controller method 'SaveEmployee' that it is update case not new record Save case.
4. Delete Saved Records
Deleting record from database in MVC is very simple and similar steps were performed as we do earlier. For that we need to follow this procedure.
1. Create Delete link
Now we will add one more column to view all records page. This column will have the link to delete respective record from our data base. So let start quickly:
Add following code to ".cshtml' file ( as per code in step "2. Adding View and Its Content").
for table header
<td><b>Delete</b></td>
and for table rows
<td>@Html.ActionLink("Delete", "DeleteRecord", new { recordID = @item.EmpId })</td>
Now you can see that we have called the 'DeleteRecord
' method on click of this action link.
Here how it looks at user end:
2. Controller Method
Now, let see what will be written to out controller method of delete record. Before that have a look for link html so created
<a href="/First/DeleteRecord?recordID=2">Delete</a>
As we are clear now that it is calling 'DeleteRecord'
method from our 'FirstController
' that accepts recordID
as parameter. The value for recordID for this very record is 2.
Here is the method for deleting the record from database.
public ActionResult DeleteRecord(int recordID)
{
StartWithMVCEntities db = new StartWithMVCEntities();
Employee objEmp = db.Employees.ToList().Find(m => m.EmpId == recordID);
db.Employees.DeleteObject(objEmp);
db.SaveChanges();
return RedirectToAction("ViewAllRecords");
}
As you can see this is quite simple to delete a record from database in MVC pattern.
Here once we deleted the record, we just re-routed the request to the method of displaying all records.
Conclusion
In these articles(part 1 and 2) we sow how can we add new, View, Update and delete the records in MVC with entity to Sql. Now, run you project and follow the steps:
>> Add New record.
>> Go To View All Records page.
>> click on edit link
>> Make changes and save.
>>Click on delete link
>>Reloaded view will have updated data.
So, this is simplest way to Save, Edit, Update record in MVC.
Points of Interest
MVC provide a whole new pattern of coding with re-usability of view with single controller. In MVC with very little efforts you can manage any large application. The best thing in MVC is you can concentrate on your part (or your responsibility) without affecting others.
As in MVC only required piece of HTML are reflected to client, so it makes it faster than other approaches.
So its always useful when you have work on larger projects.
Coming Up
What Next ? Next article will be on MVC with Ajax
Hope it will help you.All queries and Suggestions are welcome.. :)