This simple tutorial will guide you to create a small MVC application with CRUD features.
This explains how easy we can use MVC Entity framework to develop our apps.
Goal : We want to create an address with with 3 fields , Name, Email ID, Address.
We should have the option to Create, View, Update and Delete each entries.
System will create the database and tables automatically. Basically you no need to do any coding.
Source Code : https://github.com/haneefputtur/mvcHelloWorld
Step1 :
Create a new project as shown below.
Step 2:
Create a model as shown below and name it as Customer
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace HelloWorld.Models
{
public class Customer
{
[Key]
public int customer_id { get; set; }
[DisplayName("Customer Name")]
public string customer_name { get; set; }
[DisplayName("Customer Email")]
public string customer_email { get; set; }
[DisplayName("Customer Address")]
public string customer_address { get; set; }
}
}
Step 3: Build the solution to reflect the model in the application before proceed further.
Step 4: Now Right click on home controller and delete
Step 5: Repeat the same step and delete Home inside View Folder
Step 6: Now Let us create our new controller using entity frame work.
When you press Add if you get any error , Rebuild the project and try to repeat the step again.
If all success then you will see below screen
Step 7: Run the application
If success you will see below home page.
Have a look at the code which generated above view at Controller and View
public ActionResult Index()
{
return View(db.Customers.ToList());
}
// Below is the code for Index view
@model IEnumerable<HelloWorld.Models.Customer>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.customer_name)
</th>
<th>
@Html.DisplayNameFor(model => model.customer_email)
</th>
<th>
@Html.DisplayNameFor(model => model.customer_address)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.customer_name)
</td>
<td>
@Html.DisplayFor(modelItem => item.customer_email)
</td>
<td>
@Html.DisplayFor(modelItem => item.customer_address)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.customer_id }) |
@Html.ActionLink("Details", "Details", new { id=item.customer_id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.customer_id })
</td>
</tr>
}
</table>
Click Create New to add new records
After submitting few records check the listing as follows. It will also have the option for Edit, Delete and Details
Click View -> Server Explorer in the top menu to have a look at the db automatically created by MVC Entity framework.
Complete project source code available : https://github.com/haneefputtur/mvcHelloWorld