Listing with Insert and Update MVC Part 1

April 22, 2015 0 Comments

Listing of records is binding the model with custom list of objects and show on the view page. For this process we will create custom class that will be used to create objects list and then will bind that list with model.
We have learnt how to use default process and create listing with CRUD actions. In this article we will create with our own code blocks. Create a class CategoryD having all the fields saved in the database table Category as:
public class CategoryD
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public bool IsActive { get; set; }
Create a controller CategoriesController with default Index action. This action is empty and write following code fragment in this action:
public ActionResult Index()
List<CategoryD> categories = new List<CategoryD>();
using (EmpDbEntities db = new EmpDbEntities())
categories = db.Categories.Select(a => new CategoryD
Id = a.CategoryId,
Title = a.Name,
Description = a.Description,
IsActive = a.IsActive
return View(categories);
Create view for this action and paste below code in this view page:
@model CodeWallMVCApplication.ViewModels.CategoryVM
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
int i = 1;
<h2>Categories List</h2>
<input type="button" value="Create New" id="btnNew" />
@foreach (var item in Model)
<td>@(item.IsActive ? "Active" : "D")</td>
i = i + 1;
Run this project and go to this controller’s action, it will show all the records from categories table. This output is as same as the output in earlier article where the view has been created using default MVC feature.
Listing with Insert and Update MVC Part 1

This is only listing part, we have to insert and update through this same page.  To perform this, just change the category class a little bit and add one more class. We will insert and update category entity in our next article.

Jacob Lefore

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard. Google