Sunday, April 27, 2014

Scaffolding With ASP.net MVC 5

Articles Of The Day


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.

Scaffolding With ASP.net MVC 5

Step 2 :
  • Right click your Controllers folder and Add New Scaffolded Item is as below.

Scaffolding With ASP.net MVC 5

 
Step 3 :
  • From the Add Scaffold window, select the MVC 5 Controller with views,using Entity Framework scaffold template.
Scaffolding With ASP.net MVC 5



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.

Scaffolding With ASP.net MVC 5


  • 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

Scaffolding With ASP.net MVC 5



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.

Scaffolding With ASP.net MVC 5


That's it.You're done.



Let's run our sample application.
  • All the CRUD related auto generated views are as below.

Index Page
Scaffolding With ASP.net MVC 5

Create Page

Scaffolding With ASP.net MVC 5

Details Page


Scaffolding With ASP.net MVC 5

Edit Page


Scaffolding With ASP.net MVC 5

Delete Page


Scaffolding With ASP.net MVC 5



It's simply Awesome :)


  • All above CRUD operations were generated according to our Model class Pet.
  • It looks like below.

Pet.cs

public class Pet
    {
        public Pet() { Id = Guid.NewGuid(); Created = DateTime.Now; }

        public Guid Id { get; set; }

        [StringLength(50), Required]
        public string Name { get; set; }

        [ScaffoldColumn(false)]
        public DateTime Created { get; set; }

        [Display(Name = "Birth Date"), DataType(DataType.Date)]
        public DateTime? BirthDate { get; set; }

        [Required]
        public double 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 ?

Scaffolding With ASP.net MVC 5


What if you try to enter a wrong data type ?

Scaffolding With ASP.net MVC 5


Calender has been shown, if it's a DateTime property.

Scaffolding With ASP.net MVC 5



It's simply Supper  :)


Auto generated code snippet for the PetController


PetController.cs 


public class PetController : Controller
    {
        
        private DataContext db = new DataContext();//to instantiate EF context

        // GET: /Pet/
        public ActionResult Index()
        {
            return View(db.Pets.ToList());
        }


        // GET: /Pet/Details/5
        public ActionResult Details(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Pet pet = db.Pets.Find(id);
            if (pet == null)
            {
                return HttpNotFound();
            }
            return View(pet);
        }


        // GET: /Pet/Create
        public ActionResult Create()
        {
            return View();
        }


     // POST: /Pet/Create
     // To protect from overposting attacks, please enable the specific properties 
     // you want to bind to, for
     [HttpPost]
     [ValidateAntiForgeryToken]
     public ActionResult 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
        public ActionResult Edit(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(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]
     public ActionResult 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
        public ActionResult Delete(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Pet pet = db.Pets.Find(id);
            if (pet == null)
            {
                return HttpNotFound();
            }
            return View(pet);
        }


        // POST: /Pet/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult 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
        protected override void 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.

Scaffolding With ASP.net MVC 5


Important Note : If you have a problem of finding the Localdb instance,Please follow the
                                    below mentioned steps.

Step 1: 
  • Click the Add SQL Server button on SQL Server Object Explorer window.

Scaffolding With ASP.net MVC 5

Step 2 :
  • Set the Server name as (localdb)\v11.0 and click Connect.

Scaffolding With ASP.net MVC 5



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.

Scaffolding With ASP.net MVC 5


Scaffolding With ASP.net MVC 5


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#


The source code for this Article

Source Code

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.




You Might Also Like

20 comments:

  1. Thanks for this nice outline of Scaffolding! Is that right that scaffolding now comes with VS2013? Is it included in the Express for Web edition?

    I think it will also be great to see a little guide on customizing different parts of an application, which uses Scaffolding. For example, adding authorization facilities, limiting access to some of the CRUD operations based on different criteria and so on.

    ReplyDelete
    Replies
    1. Hi Alexander,

      Thanks for your feedback. :)

      About your queries: 1. Yes.I have used “Visual Studio 2013 Express for Web" Tool to generate all the code snippets for this article. You can do a lot by using this express edition.

      2. Sure. I’ll write more about how to customize scaffolding template generated code in my future articles. Please await for that. :)

      Delete
  2. Hi Brother,This Post is really need able but I don't understand in Where those data store?Bcuz just i m showing only localbd Project but u please clear at data migration and connection on Sql Server using Code first Approach.

    ReplyDelete
    Replies
    1. HI Nirob,

      Thanks for your feedback. :)

      About Your Question :

      Here I have used EF 6 Code First method.Hence it was automatically saved the data in LocalDB as shown above in my article.You can try this with the sample code which I have attached to this article.If you have any issues when you run the sample project please let me know.

      Delete
    2. Check this for Understanding Entity Framework Code First Migrations : http://www.dotnet-tricks.com/Tutorial/entityframework/R54K181213-Understanding-Entity-Framework-Code-First-Migrations.html

      Delete
    3. Thanks Brother........At last I understand this.

      Delete
    4. Hi Ali,

      Thanks, I’m glad you found it useful ! :)

      Delete
  3. Your information about asp.net frame works is really interesting and innovative. Also I want you to share latest updates about this frameworks. Can you update it in your website? Thanks for sharing
    Dot net training institute in Chennai

    ReplyDelete
  4. Thank You for Sharing Valuable Information. I like this blog and this is very informative.

    Dot Net Course in Chennai

    ReplyDelete
  5. It was really a nice article and i was really impressed by reading this article We are also providing asp.net courses Online Training. The best Online Training is one of the best Online Training institute.

    ReplyDelete
  6. It's very nice. Thnak you for sharing. .

    ReplyDelete
  7. Dot Net Training

    Thanks for your wonderful post.It is really very helpful for us and I have gathered some important information from this blog.If anyone wants to get Dot Net Training in Chennai reach FITA, rated as No.1 Dot Net Training Institutes in Chennai.

    Dot Net Training Chennai



    ReplyDelete
  8. Nice article i was really impressed by seeing this article, it was very interesting and it is very useful for me.I get a lot of great information from this blog. Thank you for your sharing this informative blog.
    Informatica Training in chennai
    QTP Training in Chennai
    Selenium Training in Chennai
    Best Big Data & Hadoop Training in Chennai

    ReplyDelete
  9. Hello Admin, this article you have written here is very informative. Thank you for that. I’m into HTML5 training in Chennai, and articles like these help me to be up to date on the technology. If anyone is interested in HTML training in Chennai can contact us.

    ReplyDelete
  10. Thanks for sharing this informative blog. If you are interested in taking .net in professional carrier visit this website.Dot Net Training in Chennai

    ReplyDelete
  11. Thanks Admin for sharing such a useful post, I hope it’s useful to many individuals for whose looking this precious information to developing their skill.
    web design training in chennai|website designing training

    ReplyDelete
  12. Looking very interesting article with wonderful information
    Now I am able to learn ASP.NET on my own.
    Thank you for giving such a nice info
    plz do keep sharing on...

    ReplyDelete

Thanks for your Feedback.