Introduction
- This Article shows how to use Scaffolding With your ASP.net MVC 5 Application.
What is Scaffolding ?
- ASP.net Scaffolding is a code generation framework for ASP.net Web applications.
- Visual Studio 2013 includes pre-installed code generators for MVC and Web API projects.
What are the Advantages of using Scaffolding ?
- Minimal or no code to create a data-driven Web applications.
- Quick development time.
- Pages that are fully functional and include display, insert, edit, delete, sorting, and paging functionalities.
- Built-in data validation that is based on the database schema.
- Filters that are created for each foreign key or Boolean fields.
How to Add a scaffolded item to ASP.net MVC 5 ?
Step 1 :
- Let's create an ASP.net MVC 5 web application in Visual Studio 2013 and name it as ScaffoldingMVC5.
Step 2 :
- Right click your Controllers folder and Add New Scaffolded Item is as below.
Step 3 :
- From the Add Scaffold window, select the MVC 5 Controller with views,using Entity Framework scaffold template.
Step 4 :
- The Add Controller window,you can give the name of your Controller (e.g. PetController),select your model class (e.g. Pet) and also you can create the Data context class (e.g. DataContext) as below.
- All other options are put as default.
- After that click Add button.
- When you click the New data context.. button on Add Controller box above,it will pop up the below New Data Context box.
- From there you can give a name for your Data context is as below.
- e.g. DataContext
Step 5 :
- The solution tree shows the relevant classes and pages were created for above example.
- For example, the following image shows the MVC controller (i.e. PetController) and Views (i.e. Inside the Pet folder) that were created through scaffolding for a Model class named Pet.
That's it.You're done.
Let's run our sample application.
- All the CRUD related auto generated views are as below.
Index Page
Details Page
Edit Page
Delete Page
It's simply Awesome :)
Key points of the above code
Calender has been shown, if it's a DateTime property.
Edit Page
Delete Page
It's simply Awesome :)
- All above CRUD operations were generated according to our Model class Pet.
- It looks like below.
Pet.cs
publicclassPet
{
public Pet() { Id = Guid.NewGuid(); Created = DateTime.Now; }
publicGuid Id { get; set; }
[StringLength(50), Required]
publicstring Name { get; set; }
[ScaffoldColumn(false)]
publicDateTime Created { get; set; }
[Display(Name = "Birth Date"), DataType(DataType.Date)]
publicDateTime? BirthDate { get; set; }
[Required]
publicdouble Weight { get; set; }
}
Key points of the above code
- [ScaffoldColumn(false)] means,the property which it declared will not use for scaffolding.In other words, that property will not be shown on the UI (i.e. Created property will not be shown).
- Data validations of the form elements are happening ,according to the above model's Data Annotation values.
- Let's explore it.
If you click the Create button, without entering anything.What will happen ?
What if you try to enter a wrong data type ?
Calender has been shown, if it's a DateTime property.
It's simply Supper :)
Auto generated code snippet for the PetController
PetController.cs
publicclassPetController : Controller { privateDataContext db = newDataContext();//to instantiate EF context
// GET: /Pet/ publicActionResult Index() { return View(db.Pets.ToList()); }
// GET: /Pet/Details/5 publicActionResult Details(Guid? id) { if (id == null) { returnnewHttpStatusCodeResult(HttpStatusCode.BadRequest); } Pet pet = db.Pets.Find(id); if (pet == null) { return HttpNotFound(); } return View(pet); }
// GET: /Pet/Create publicActionResult Create() { return View(); }
// POST: /Pet/Create // To protect from overposting attacks, please enable the specific properties
// you want to bind to, for [HttpPost] [ValidateAntiForgeryToken] publicActionResult Create([Bind(Include = "Id,Name,Created,BirthDate,Weight")] Pet pet) { if (ModelState.IsValid) { pet.Id = Guid.NewGuid(); db.Pets.Add(pet); db.SaveChanges(); return RedirectToAction("Index"); }
return View(pet); }
// GET: /Pet/Edit/5 publicActionResult Edit(Guid? id) { if (id == null) { returnnewHttpStatusCodeResult(HttpStatusCode.BadRequest); }
Pet pet = db.Pets.Find(id); if (pet == null) { return HttpNotFound(); } return View(pet); }
// POST: /Pet/Edit/5 // To protect from overposting attacks, please enable the specific properties
// you want to bind to, for [HttpPost] [ValidateAntiForgeryToken] publicActionResult Edit([Bind(Include = "Id,Name,Created,BirthDate,Weight")] Pet pet) { if (ModelState.IsValid) { db.Entry(pet).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(pet); }
// GET: /Pet/Delete/5 publicActionResult Delete(Guid? id) { if (id == null) { returnnewHttpStatusCodeResult(HttpStatusCode.BadRequest); }
Pet pet = db.Pets.Find(id); if (pet == null) { return HttpNotFound(); } return View(pet); }
// POST: /Pet/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] publicActionResult DeleteConfirmed(Guid id) { Pet pet = db.Pets.Find(id); db.Pets.Remove(pet); db.SaveChanges(); return RedirectToAction("Index"); }
// To make sure that database connections are properly closed and the
// resources they hold freed up protectedoverridevoid Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } }
PetController.cs
publicclassPetController : Controller
{
privateDataContext db = newDataContext();//to instantiate EF context
// GET: /Pet/
publicActionResult Index()
{
return View(db.Pets.ToList());
}
// GET: /Pet/Details/5
publicActionResult Details(Guid? id)
{
if (id == null)
{
returnnewHttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pet pet = db.Pets.Find(id);
if (pet == null)
{
return HttpNotFound();
}
return View(pet);
}
// GET: /Pet/Create
publicActionResult Create()
{
return View();
}
// POST: /Pet/Create
// To protect from overposting attacks, please enable the specific properties
// you want to bind to, for
// you want to bind to, for
[HttpPost]
[ValidateAntiForgeryToken]
publicActionResult Create([Bind(Include = "Id,Name,Created,BirthDate,Weight")] Pet pet)
{
if (ModelState.IsValid)
{
pet.Id = Guid.NewGuid();
db.Pets.Add(pet);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(pet);
}
// GET: /Pet/Edit/5
publicActionResult Edit(Guid? id)
{
if (id == null)
{
returnnewHttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pet pet = db.Pets.Find(id);
if (pet == null)
{
return HttpNotFound();
}
return View(pet);
}
// POST: /Pet/Edit/5
// To protect from overposting attacks, please enable the specific properties
// you want to bind to, for
// you want to bind to, for
[HttpPost]
[ValidateAntiForgeryToken]
publicActionResult Edit([Bind(Include = "Id,Name,Created,BirthDate,Weight")] Pet pet)
{
if (ModelState.IsValid)
{
db.Entry(pet).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(pet);
}
// GET: /Pet/Delete/5
publicActionResult Delete(Guid? id)
{
if (id == null)
{
returnnewHttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pet pet = db.Pets.Find(id);
if (pet == null)
{
return HttpNotFound();
}
return View(pet);
}
// POST: /Pet/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
publicActionResult DeleteConfirmed(Guid id)
{
Pet pet = db.Pets.Find(id);
db.Pets.Remove(pet);
db.SaveChanges();
return RedirectToAction("Index");
}
// To make sure that database connections are properly closed and the
// resources they hold freed up
// resources they hold freed up
protectedoverridevoid Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
Key points of the above code
- This code snippet is self explanatory.It shows how to handle CRUD operations with Pet Model.
- The first line of the above code snippet instantiates the entity framework data context object.(i.e. private DataContext db = new DataContext())
- It uses Entity Framework Code First approach to access database objects.
- To make sure that database connections are properly closed and the resources they hold freed up, you have to dispose the context instance when you are done with it. That is why the scaffolded code provides a Dispose method at the end of the PetController controller. (i.e. protected override void Dispose(bool disposing){})
Where were those data stored ?
- It has been stored inside the Localdb.
- To check that,Open the SQL Server Object Explorer inside the Visual Studio 2013 is as below.
Important Note :If you have a problem of finding the Localdb instance,Please follow the
below mentioned steps.
Step 1:
That's it.You're done :)
How to View the Stored Data ?
below mentioned steps.
Step 1:
- Click the Add SQL Server button on SQL Server Object Explorer window.
Step 2 :
That's it.You're done :)
How to View the Stored Data ?
- Just select the Pets table from the DataContext Database.
- And Right click it and choose the View Data menu item.
Yep,That's it.Well done :)
Used Dev Environment in Article's Source Code
- Visual Studio 2013 Express for Web
- .Net Framework 4.5.1
- ASP.net MVC 5
- C#
Conclusion
- You saw that how easily you can create an ASP.net MVC 5 apps by using this latest Scaffolding built in code generation framework.
- If you use scaffolding, then you can reduce the amount of time to develop standard data operations in your project.
- So now you can use this awesome scaffolding feature to develop your next small scale app within a few hours of work.It's pretty Cool.Try it.
- So enjoy the characteristics of this Awesome code generation framework.
I hope this helps to You.Comments and feedback greatly appreciated.
If you feel it was a good article,Give me a +1.Thank You.