Sunday

Dropdown List: Cascading Dropdown list in MVC

Introduction

Today, I am explaining about cascading drop down list in MVC, while we are working on CRM, ERP, Web Apps or other web apps then we often require to populate cascading dropdown list e.g. First populate Country then select country from list then corresponding state will be populated in other dropdown. This is the way that how we need cascading dropdown list in our MVC applications. Here I am taking example, first populating drop down list of classes, on the click of classes, the other drop down list will be populated of Subjects and then while we click on Subjects then chapter will be populated correspondingly.

Add Entity Framework Model in MVC Project

First of all, you have to add entities in our project to populate cascading drop down in our project. I am providing a video link (Add Entities) which explains all steps how to add entities in our project using entity framework.

namespace MvcApplication1.Context
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    
    public partial class MVC_AppEntities1 : DbContext
    {
        public MVC_AppEntities1()
            : base("name=MVC_AppEntities1")
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
    
        public virtual DbSet tblChapterMasters { get; set; }
        public virtual DbSet tblClassMasters { get; set; }
        public virtual DbSet tblSubjectMasters { get; set; }
    }
}

Populate First Dropdown List (Subjects)

Here I have written an action method in controller as below:
[HttpGet]
public ActionResult My_MVC_App(string ddlClasses, string ddlSubjects, string ddlChapters)
{
    var _context = new MVC_AppEntities1();
    List _classlst = GetClasses();

   // Clases
   List li = new List();
   foreach (var item in _classlst)
   {
   li.Add(new SelectListItem { Text = item.ClassName, Value = item.ClassIDPK.ToString() });
   }
   ViewData["Classes"] = li;

   return View();
}

Populate Second Dropdown List (Subjects)

Next step is to write action method to populate second dropdown list of subject while we click on classes drop down list.
[HttpGet]
public JsonResult GetSubjectsNew(Int16 ClassID)
{
    List _lstSubjects = GetSubjectsID(ClassID);
    List _liSubj = new List();
    /// 
    var _context = new MVC_AppEntities1();
foreach (var _itemsubject in _lstSubjects)
{
  _liSubj.Add(new SelectListItem { Text = _itemsubject.SubjectName, Value = _itemsubject.SubjectIDPK.ToString() });
}

return Json(new SelectList(_liSubj, "Value", "Text"), JsonRequestBehavior.AllowGet);
  

Populate Third Dropdown List (Chapter)

Now next step is to populate third dropdown list of chapters while we click on subjects correspondingly.

 [HttpGet]
 public JsonResult GetChapterList(Int16 SubjectID, Int32? ChapterID)
{
   List _lstChapters = GetChapters(SubjectID);
   List _liSubj = new List();

   foreach (var _itemsubject in _lstChapters)
   {
     _liSubj.Add(new SelectListItem { Text = _itemsubject.ChapterName, Value = _itemsubject.ChapterIDPK.ToString() });
   }
   return Json(new SelectList(_liSubj, "Value", "Text"), JsonRequestBehavior.AllowGet);
}

Helping Method to Populate All Dropdowns (Classes, Subjects, Chapters)

Helping Methods

I have explained below three helping methods to populate all drop downs correspondingly.

MVC Razor View
Now I am talking about MVC razor view where we are playing with all three drop downs interface.

Import Jquery Library in our Project (Under Head Tag)


Head Tag

MVC Razor HTML Helpers

Below is written code to provide complete interface to populate three dropdowns.

razor view

Jquery Ajax call to MVC Controller

Here is written a Ajax/Jquery method to call Controller action for for subjects

Class Jquery Ajax Call

Here is written other Ajax/Jquery method to call Controller action for the chapters as below:

Chapter Jquery Ajax Call

Conclusion

Explained above about cascading dropdown in MVC with concerned every aspect of the MVC apps. Cascading dropdown is the common requirement of our each MVC applications, if we skip few steps to cascading drop down then sometimes it waste our very precious time of development.

Development Environment

Visual Studio 2013, Entity Framework 6.0, Database script under app folder App_Data, Change web.config settings according to your machine specific, Data source, Initial Catalog, Database User ID, Password etc.

Download Complete Project

Download

Relevant Reading

Entity Framework Error: Compiling transformation metadata file entity framework

Introduction

Compiling transformation metadata file entityframework.dll could not be found, this issue comes out while our solution pointing to entityframework.dll on wrong location. It needs correct to right location. I have explained all steps one by one following way.

Error Description

Error 1 Compiling transformation: Metadata file 'C:\Program Files\Microsoft Visual Studio 12.0\Common7\IDE..\IDE\EntityFramework.dll' could not be found F:\EF\WebApplication1\WebApplication1\Model1.tt 1 1 WebApplication1

Saturday

Exception: System Data Entity Infrastructure DbUpdateException

Introduction

I was working on MVC application using Entity Framework, MVC, Jquery. I hit the Save button to save corresponding values into database, but this time did not go fine as usual, I got the given error An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code.

Error Description

An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code

Solution

When I started working to resolve issue, debugging deeply and came across of stack trace message then I found that this issue was due to database table identity off.

Table Identity off

I just set table Identity on and again tried to save relevant values into database, this time it worked fine for me.
Table Identity On

Conclusion

Another very good experience of MVC, Entity Framework, Jquery application. Every time, in every new application often comes new issues. From these issues, we learnt a new lesson every time and smoothing way to next time. Above, I have explained in detail how can we resolve issue of An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code. If you still find the same issue, please don't forget to write me here.

Suggested Reading


Sunday

Error CS1963: An expression tree may not contain a dynamic operation

Introduction

I was working on a MVC Application (Razor Engine) using with Entity Framework. I triggered an error not able to populate entities while binding the controls with the database. I have written below detail of error as follows:

Error Description

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 

Compiler Error Message: CS1963: An expression tree may not contain a dynamic operation

TempData vs ViewData vs ViewBag

Introduction

Today, I am explaining about TempData vs ViewData vs Viewbag while working in MVC. All three (TempData, ViewData,  ViewBag) terms are used to pass data from controller to View. These all have different  capability to preserve data while passing from Controller to View using MVC application.

ViewBag

  1. ViewBag is used dynamically to pass the data from controller to view.
  2. It is being introduced since C# 4.0 .Net Framework.
  3. ViewData is property of ControllerBase Class in from .Net Framework 4.5 C#.
  4. ViewBag life span is very short. It only lies under current request.
  5. If it redirects then its value becomes null.
  6. It does not required to typecasting for getting data from Controller to View.
  7. ViewBag is slower than ViewData.

Jquery Validation: Email Validation using Jquery

Introduction

This is my second post on Jquery Validation, In my previous post, I explained in detail about Numeric Validation using Jquery, now I am going to explain about Email Validation using Jquery.

Input Box to input Email




Jquery Validation: Numeric Validation using Jquery

Introduction

Today, I am going to explain about numeric validation using Jquery. Jquery plays a great role to validate data at client side without refreshing whole the page. To make your application more user friendly, interactive and soothing then Jquery plays a vital role to fulfill your dreams.
Data Input Text Box

Number :