TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

ASP.Net MVC Scaffolding

ASP.Net MVC Scaffolding with asp.net tutorial, asp.net introduction, features, project, example, server controls, labels, textbox, button, hyperlink, radiobutton, calender, checkbox, fileupload, events handling, authentication, webforms model binding, html server control, compare validdator, range validator, validation summary, mvc introduction, mvc project, view, validation, entity framework, authentication etc.

<< Back to ASP

ASP.NET MVC Scaffolding

It is a feature of ASP.NET that allows us to generate functional code rapidly. It is also known as code generator framework. It is pre-installed in Visual Studio 2013 and higher version.

To create basic CRUD application, scaffolding is best choice. It reduces time amount and generate clean code. Here, we are using scaffolding to develop CRUD application.

ASP.NET CRUD Example

This example consist couple of steps that are given below.

  1. Create New Project
  2. Select File menu from menu bar and select New->Project. We can also use shortcut Ctrl+Shift+N to create a new project.

    ASP Scaffolding 1

    This will pop up a window of that contains projects. We are selecting ASP.NET Web Application.

    ASP Scaffolding 2

    After clicking ok, it pops up a new window of templates. Here, we are selecting MVC template which is used to create MVC web application.

    ASP Scaffolding 3

    Hit ok then it will create a project and shows a progress bar as shown below.

    ASP Scaffolding 4

    CRUD Project Structure

    ASP Scaffolding 5

    We can run this application by pressing Ctrl+F5. It will produce a default index page to the browser that looks like the below.

    ASP Scaffolding 6

    To create complete crud, we need to add Models, Views and Controller in our project. Here, we are creating a Model that deals with data.

  3. Create a New Model
  4. We are creating a Student Model inside Models folder of our project. Right click on the Models folder and select add->class that will pop up a dialog box. Create class by providing name.

    ASP Scaffolding 7

    This model class has some source code, modify its code as we did below.

    // Student.cs

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Web;
    namespace CrudExample.Models
    {
    public class Student
        {
    public int ID { get; set; }
            [Required]
    public string Name { get; set; }
            [Required]
            [EmailAddress]
    public string Email { get; set; }
            [Required]
    public string Contact { get; set; }
        }
    }
    
  5. Create a Context Class
  6. We are creating another class inside the Models folder, it is used to communicate with Entity Framework and perform database operations. This class inherits DbContext class.

    // StudentRecord.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Data.Entity.ModelConfiguration.Conventions;
    using System.Data.Entity;
    namespace CrudExample.Models
    {
    public class StudentRecord : DbContext
        {
    public DbSet Students { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Conventions.Remove();
            }
        }
    }
    
  7. Add Scaffold to the Project
  8. Right click on the Controllers folder and add scaffold as we did in the screen shoot.

    ASP Scaffolding 8

    It will pop up the following dialog box. Select controller with Entity Framework.

    ASP Scaffolding 9

    And click Add button. It asks for Model and context name. Fill the entries and click ok.

    ASP Scaffolding 10

    After clicking add button, it creates a StudentsController controller and a Students folder. The Students folder contains web pages for the each CRUD operation.

    // StudentsController.cs

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Entity;
    using System.Linq;
    using System.Net;
    using System.Web;
    using System.Web.Mvc;
    using CrudExample.Models;
    namespace CrudExample.Controllers
    {
    public class StudentsController : Controller
        {
    private StudentRecord db = newStudentRecord();
    // GET: Students
    public ActionResult Index()
            {
    return View(db.Students.ToList());
            }
    // GET: Students/Details/5
    public ActionResult Details(int? id)
            {
    if (id == null)
                {
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
    Student student = db.Students.Find(id);
    if (student == null)
                {
    return HttpNotFound();
                }
    return View(student);
            }
    // GET: Students/Create
    public ActionResult Create()
            {
    return View();
            }
    // POST: Students/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
            [HttpPost]
            [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ID,Name,Email,Contact")] Student student)
            {
    if (ModelState.IsValid)
                {
                    db.Students.Add(student);
                    db.SaveChanges();
    return RedirectToAction("Index");
                }
    return View(student);
            }
    // GET: Students/Edit/5
    public ActionResult Edit(int? id)
            {
    if (id == null)
                {
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
    Student student = db.Students.Find(id);
    if (student == null)
                {
    return HttpNotFound();
                }
    return View(student);
            }
    // POST: Students/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
            [HttpPost]
            [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "ID,Name,Email,Contact")] Student student)
            {
    if (ModelState.IsValid)
                {
                    db.Entry(student).State = EntityState.Modified;
                    db.SaveChanges();
    return RedirectToAction("Index");
                }
    return View(student);
            }
    // GET: Students/Delete/5
    public ActionResult Delete(int? id)
            {
    if (id == null)
                {
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
    Student student = db.Students.Find(id);
    if (student == null)
                {
    return HttpNotFound();
                }
    return View(student);
            }
    // POST: Students/Delete/5
            [HttpPost, ActionName("Delete")]
            [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
            {
    Student student = db.Students.Find(id);
                db.Students.Remove(student);
                db.SaveChanges();
    return RedirectToAction("Index");
            }
    protected override void Dispose(bool disposing)
            {
    if (disposing)
                {
                    db.Dispose();
                }
    base.Dispose(disposing);
            }
        }
    }
    

    The Students folder inside the View contains the following files.

    ASP Scaffolding 11

    The Index.cshtml file contains the following code.

    // Index.cshtml

    @model IEnumerable<scaffoldingTest.Models.Student>
    @{
        ViewBag.Title = "Index";
    }
    <h2>Index</h2>
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <table class="table">
    <tr>
    <th>
                @Html.DisplayNameFor(model => model.Name)
    </th>
    <th>
                @Html.DisplayNameFor(model => model.Email)
    </th>
    <th>
                @Html.DisplayNameFor(model => model.Contact)
    </th>
    <th></th>
    </tr>
    @foreach (var item in Model) {
    <tr>
    <td>
                @Html.DisplayFor(modelItem => item.Name)
    </td>
    <td>
                @Html.DisplayFor(modelItem => item.Email)
    </td>
    <td>
                @Html.DisplayFor(modelItem => item.Contact)
    </td>
    <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
                @Html.ActionLink("Details", "Details", new { id=item.ID }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.ID })
    </td>
    </tr>
    }
    </table>
    

    Output:

    Right click on the Index.cshtml file and select "view in browser", this will execute file and produce the following output.

    // Index file

    This index file is used to show student record. Currently table is empty, so it does not show any data.

    ASP Scaffolding 12

    Add new Student

    We can add new student by clicking on the Create New button. This will redirect to a student form.

    ASP Scaffolding 13

    After adding it, we added two more entries then redirect back to the index file. Now, it contains three student record.

    ASP Scaffolding 14

    Update Record

    We can update record by clicking on the Edit button. This will redirect to the update form. The following screenshot shows the edit page.

    ASP Scaffolding 15

    After updating record index page looks like this:

    ASP Scaffolding 16

    Delete Record

    We can delete any record simply by clicking on the provided Delete link. Let's delete Roman Johnfrom the table. A confirmation message is display to the user for surety.

    ASP Scaffolding 17

    After clicking on the Delete button, it redirects to the index page that contains the remaining records.

    ASP Scaffolding 18

    We can see that there are only two records are present.






Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf