How to implement MVC with ASP.Net and C#


Database work to do as below:

Table Creation


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CityMaster]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[CityMaster]
GO
CREATE TABLE [dbo].[CityMaster] (
[citycode] [int] IDENTITY (1, 1) NOT FOR REPLICATION NOT NULL ,
[cityname] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]
GO

Let us start with actual topic as how to implement MVC with ASP.Net and C#.

I will assume that you have installed Microsoft Data Access Block For .Net on your machine you can download form Microsoft site.
Follow the steps as

Create new project with name "Mvc"
  • Right click on solution
  • Add
  • New Project
Select Class Library under Visual C# project. Give Library Name as: MVCLibDefination

Similarly you need to follow above steps for "MVCLibFramwork" and "MVCLibBusinessObjects" .

MVCLibDefination: -
  1. Create a project with the name MVCLibDefination.
  2. Create business (file name: IBusiness.cs), entity (file name: IBusinessEntity.cs), logic (file Name: IbusinessLogic.cs ) classes.
    Business definition class: -

    using System;
    using System.Collections;
    namespace MVCLibDefination
    {
              /// <summary>
              /// Summary description for IBusiness.
              /// </summary>
              public interface IBusiness
              {
                       bool Insert(object GenObj);
                       bool Update(object GenObj);
                       bool Delete(object GenObj);
                       bool DataExists(object GenObj);
                       ArrayList GetData(object GenObj);
              }
    }


    Business Entity Class: -

    using System;
    namespace MVCLibDefination
    {
              /// <summary>
              /// Summary description for IBusinessEntity.
              /// </summary>
              public interface IBusinessEntity
              {
                       object GeneralObj
                       {
                                 get;
                                 set;
                       }
                      
              }
    }


    Business Login Class which implements Business definition class: -

    using System;
    namespace MVCLibDefination
    {
              /// <summary>
              /// Summary description for IbusinessLogic.
              /// </summary>
              public interface IbusinessLogic : IBusiness
              {
             
              }
    }

  3. Click on Build->Build MVCLibDefination

    MVCLibFramwork: -
     
    1. Create Project with the name MVCLibFramwork.
    2. Add MVCLibDefination.dll to the references.
    3. Create Business Entity file (file name: BusinessEntity.cs).

    using System;
    using MVCLibDefination;
    namespace MVCLibFramwork
    {
          /// <summary>
          /// Summary description for BusinessEntity.
          /// </summary>
          public abstract class BusinessEntity : IBusinessEntity
          {
                private object generalObj;
                public object GeneralObj
                {
                      get
                      {
                            return this.generalObj;
                      }
                      set
                      {
                            this.generalObj=value;
                      }
                }
    //          public BusinessEntity()
    //          {
    //                //
    //                // TODO: Add constructor logic here
    //                //
    //          }
          }
    }

     
  4. Create Business Logic file (File name: BusinessLogic.cs).

    using System;
    using System.Collections;
    using MVCLibDefination;
    namespace MVCLibFramwork
    {
          /// <summary>
          /// Summary description for BusinessLogic.
          /// </summary>
          public class BusinessLogic : IBusiness
          {
                private IBusinessEntity ibusinessEntity = null;
                public BusinessLogic()
                {
                      //
                      // TODO: Add constructor logic here
                      //
                }
                public IBusinessEntity BusinessEntity
                {
                      get
                      {
                            return ibusinessEntity;
                      }
                      set
                      {
                            ibusinessEntity=value;
                      }
                }
                #region IBusiness Members

                bool IBusiness.Insert(object GenObj)
                {
                      return true;
                }
                bool IBusiness.Update(object GenObj)
                {
                      return true;
                }
                bool IBusiness.Delete(object GenObj)
                {
                      return true;
                }
                bool IBusiness.DataExists(object GenObj)
                {
                      return true;
                }
                ArrayList IBusiness.GetData(object GenObj)
                {
                      ArrayList arlist=new ArrayList();
                      return arlist;
                }
                #endregion
     
          }
    }
     
  5. Create Business Service file (file name: BusinessService.cs).

    using System;
    using MVCLibDefination;
    using System.Collections;
    namespace MVCLibFramwork
    {
          /// <summary>
          /// Summary description for BusinessService.
          /// </summary>
          ///
          public enum OperationType
          {
                Create, Update, Read, Delete,Exists
          }

          public class BusinessService
          {
                private IBusinessEntity ibusinessEntity=null;
                private IbusinessLogic iBusinessLogic=null;
                public IbusinessLogic BusinessLogic
                {
                      get
                      {
                            return iBusinessLogic;
                      }
                      set
                      {
                            this.iBusinessLogic=value;
                      }
                }
                public IBusinessEntity BusinessEntity
                {
                      get
                      {
                            return ibusinessEntity;
                      }
                      set
                      {
                            this.ibusinessEntity=value;
                      }
                }
                public ArrayList GetExistingData(object genObj)            {
                      ArrayList arylist=new ArrayList();
                      arylist=iBusinessLogic.GetData(genObj);
                      return arylist;
                }
                public bool Execute(OperationType operationType,object genObj)
                {
                      //object vEmpMaster=null;
                      bool blnflag=false;
                      switch (operationType)
                      {
                            case OperationType.Create:
                                  blnflag=iBusinessLogic.Insert(genObj);
                                  break;

                            case OperationType.Update:
                                  blnflag=iBusinessLogic.Update(genObj);
                                  break;
                            case OperationType.Delete:
                                  blnflag=iBusinessLogic.Delete(genObj);
                                  break;
                            case OperationType.Exists:
                                  blnflag=iBusinessLogic.DataExists(genObj);
                                  break;

                      }
                      return blnflag;
                }
    //          public BusinessService()
    //          {
    //                //
    //                // TODO: Add constructor logic here
    //                //
    //          }
          }
    }

  6. Click on build->Build MVCLibFramwork.
MVCLibBusinessObjects: -
  1. Create a Project with the name MVCLibBusinessObjects.
  2. Add MVCLibDefination.dll and MVCLibFramwork.dll to the references.
  3. Create dbBroker Class which contain database connection string (dbBroker.cs).

    using System;
    using MVCLibDefination;
    using MVCLibFramwork;

    namespace MVCLibBusinessObjects
    {
          /// <summary>
          /// Summary description for dbBroker.
          /// </summary>
          public class dbBroker
          {
                public String getConnectionString()
                {
                      String strConn="";
                      strConn="server=pol005;user Id=haritha;password=haritha;database=haritha;Pooling=yes;Min Pool Size=0;Max Pool Size=25;Connect Timeout=90";
                      return strConn;

                }
          }
    }


    4. Create CityMaster Entity class (file name CityMaster.cs).

    using System;
    using MVCLibBusinessObjects;
    using MVCLibDefination;
    using MVCLibFramwork;
    namespace MVCLibBusinessObjects
    {
          /// <summary>
          /// Summary description for CityMaster.
          /// </summary>
          public class CityMaster : BusinessEntity
          {
                private int vCityCode=0;
                private String vCityName="";
                public int CityCode
                {
                      get
                      {
                            return vCityCode;
                      }
                      set
                      {
                            vCityCode=value;
                      }
                }
                public String CityName
                {
                      get
                      {
                            return vCityName;
                      }
                      set
                      {
                            vCityName=value;
                      }
                }

          }
    }


    5. Create CityMaster Business Class (CityMasterBO.cs).

    Note: We are making use of "Microsoft.ApplicationBlocks.Data" namespace in below class

    using System;
    using MVCLibDefination;
    using MVCLibFramwork;
    using Microsoft.ApplicationBlocks.Data;
    using System.Data;
    using System.Data.SqlClient;
    using System.Collections;
    using System.Web;
    using System.Web.UI;
    namespace MVCLibBusinessObjects
    {
          /// <summary>
          /// Summary description for CityMasterBO.
          /// </summary>
          public class CityMasterBO : BusinessLogic, IbusinessLogic
          {
                String strConn="";
                String strQuery="";
                CityMaster varCityMaster=new CityMaster();
                ArrayList IBusiness.GetData(object vCityMaster)
                {
                ArrayList arylist=new ArrayList();
                      varCityMaster=(CityMaster) vCityMaster;
                      dbBroker dbb=new dbBroker();
                      strConn= dbb.getConnectionString(); //dbb.getConnectionStr.ToString();
                      try
                      {
                            if (varCityMaster.CityCode==0)
                            {
                                  strQuery="select citycode,cityname from citymaster";
                            }
                            else
                            {
                                  strQuery="select citycode,cityname from citymaster where
    citycode=" + varCityMaster.CityCode ;
                            }
                            SqlDataReader rdrSql;
                            rdrSql=SqlHelper.ExecuteReader(strConn,CommandType.Text,strQuery);
                            while (rdrSql.Read())
                            {
                                  int intCityCode=rdrSql.GetInt32(0);
                                  String strCityName=rdrSql.GetString(1);
                                  CityMaster cm=new CityMaster();
                                  cm.CityCode=intCityCode;
                                  cm.CityName=strCityName;
                                  arylist.Add(cm);

                            }
                            rdrSql.Close();
                      }
                      catch(Exception exp)
                      {
                            HttpContext.Current.Response.Write("Error : " + exp.ToString());
                      }
                      return arylist;
                }
                bool IBusiness.DataExists(object vCityMaster)
                {
                      bool blnflag=false;
                      try
                      {
                            dbBroker dbb=new dbBroker();
                            strConn= dbb.getConnectionString(); //dbb.getConnectionStr.ToString();
                            //HttpContext.Current.Response.Write("Conn : " + strConn);
                          
      varCityMaster=(CityMaster) vCityMaster;

                             strQuery="select count(*) from CityMaster where cityname='" + varCityMaster.CityName.ToUpper().Trim() + "'";
                           
                            int intCnt=0;
                            //HttpContext.Current.Response.Write("Query : " + strQuery);
                           
                            intCnt= (int) SqlHelper.ExecuteScalar(strConn,CommandType.Text,strQuery);
                            if (intCnt>0)
                            {
                                  blnflag=true;
                            }
                      }
                      catch(Exception exp)
                      {
                            HttpContext.Current.Response.Write("Error : " + exp.ToString());
                      }
                      return blnflag;
                }
                bool IBusiness.Insert(object vCityMaster)
                {
                      bool blnflag=false;
                      dbBroker dbb=new dbBroker();
                      strConn= dbb.getConnectionString(); //dbb.getConnectionStr.ToString();
                      SqlConnection cnnCon=new SqlConnection();
                      cnnCon.ConnectionString=strConn;
                      if (cnnCon.State==ConnectionState.Closed)
                      {
                            cnnCon.Open();
                      }
                      SqlTransaction sqlTrans=cnnCon.BeginTransaction();
                      try
                      {
                            varCityMaster=(CityMaster) vCityMaster;
                            strQuery="insert into CityMaster(cityname) values('" + varCityMaster.CityName.ToUpper().ToString() + "')";
                            SqlHelper.ExecuteNonQuery(sqlTrans,CommandType.Text,strQuery);
                            sqlTrans.Commit();
                            blnflag=true;
                      }
                      catch(Exception exp)
                      {
                            HttpContext.Current.Response.Write("Error : " + exp.ToString());
                            sqlTrans.Rollback();
                      }
                      return blnflag;
                }
                bool IBusiness.Update(object vCityMaster)
                {
                      bool blnflag=false;
                      dbBroker dbb=new dbBroker();
                      strConn= dbb.getConnectionString(); //dbb.getConnectionStr.ToString();
                      SqlConnection cnnCon=new SqlConnection();
                      cnnCon.ConnectionString=strConn;
                      if (cnnCon.State==ConnectionState.Closed)
                      {
                            cnnCon.Open();
                      }
                      SqlTransaction sqlTrans=cnnCon.BeginTransaction();
                      try
                      {
                            varCityMaster=(CityMaster) vCityMaster;
                            strQuery="update CityMaster set cityname='"+ varCityMaster.CityName.ToUpper().ToString() + "' where citycode="+ varCityMaster.CityCode;
                            SqlHelper.ExecuteNonQuery(sqlTrans,CommandType.Text,strQuery);
                            sqlTrans.Commit();
                            blnflag=true;
                      }
                      catch(Exception exp)
                      {
                            HttpContext.Current.Response.Write("Error : " + exp.ToString());
                            sqlTrans.Rollback();
                      }
                      return blnflag;
                }
                bool IBusiness.Delete(object vCityMaster)
                {
                      bool blnflag=false;
                      dbBroker dbb=new dbBroker();
                      strConn= dbb.getConnectionString(); //dbb.getConnectionStr.ToString();
                      SqlConnection cnnCon=new SqlConnection();
                      cnnCon.ConnectionString=strConn;
                      if (cnnCon.State==ConnectionState.Closed)
                      {
                            cnnCon.Open();
                      }
                      SqlTransaction sqlTrans=cnnCon.BeginTransaction();
                      try
                      {
                            varCityMaster=(CityMaster) vCityMaster;
                            strQuery="delete from CityMaster where citycode="+ varCityMaster.CityCode;
                            SqlHelper.ExecuteNonQuery(sqlTrans,CommandType.Text,strQuery);
                            sqlTrans.Commit();
                            blnflag=true;
                      }
                      catch(Exception exp)
                      {
                            HttpContext.Current.Response.Write("Error : " + exp.ToString());
                            sqlTrans.Rollback();
                      }
                      return blnflag;

                }
          }
    }

How to use above layers in Web Appliation: -
  1. Create a new Project.
  2. Create a aspx file (file name : frmCityMaster.aspx).

    image1.gif
     
  3. Write Code.

    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.Collections.Specialized;
    using MVCLibDefination;
    using MVCLibFramwork;
    using MVCLibBusinessObjects;

    namespace HarithaTestPrj.MVC_Examples
    {
          /// <summary>
          /// Summary description for frmCityMaster.
          /// </summary>
          public class frmCityMaster : System.Web.UI.Page
          {
                protected System.Web.UI.WebControls.HyperLink HyperLink1;
                protected System.Web.UI.WebControls.Label lblmode;
                protected System.Web.UI.WebControls.Label Label5;
                protected System.Web.UI.WebControls.Label lblMessage;
                protected System.Web.UI.WebControls.Button btnSave;
                protected System.Web.UI.WebControls.DropDownList dblExistingCities;
                protected System.Web.UI.WebControls.TextBox txtCityName;
                protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;
                protected System.Web.UI.WebControls.Label Label1;

                private void Page_Load(object sender, System.EventArgs e)
                {
                      // Put user code to initialize the page here
                      if (!IsPostBack)
                      {
                            NameValueCollection col1;
                            col1=Request.QueryString;
                            String[] arr1 = col1.AllKeys;
                            String strMode=col1.GetValues(arr1[0])[0];
                            lblmode.Text=strMode;
                            getExistingCityNames();
                            if ((lblmode.Text=="Edit") || (lblmode.Text=="Delete"))
                            {
                                  if (dblExistingCities.Items.Count>0)
                                  {
                                        showCityName();
                                  }
                            }
                      }
                }
                private void getExistingCityNames()
                {
                      CityMaster cm=new CityMaster();
                      cm.CityCode=0;
                      cm.CityName="";
                      ArrayList arylist=new ArrayList();
                      IbusinessLogic iBLogic=new CityMasterBO();
                      IBusinessEntity iBEntity=new CityMaster();
                      BusinessService bService=new BusinessService();
                      bService.BusinessEntity=iBEntity;
                      bService.BusinessLogic=iBLogic;
    //                bool blnExists=bService.Execute(OperationType.Exists,cm);
    //                //lblMessage.Text=blnExists.ToString();
    //                if (blnExists==true)
    //                {
                            arylist=bService.GetExistingData(cm);
                            System.Collections.IEnumerator myEnum=arylist.GetEnumerator();
                            while (myEnum.MoveNext())
                            {
                                  cm=(CityMaster) myEnum.Current;
                                  int intCityCode=cm.CityCode;
                                  String strCityName=cm.CityName;
                                  ListItem litem=new ListItem();
                                  litem.Value=intCityCode.ToString();
                                  litem.Text=strCityName;
                                  dblExistingCities.Items.Add(litem);
                            }
    //                }
                }
                private void showCityName()
                {
                      txtCityName.Text=dblExistingCities.SelectedItem.Text;
                }
                #region Web Form Designer generated code
                override protected void OnInit(EventArgs e)
                {
                      //
                      // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                      //
                      InitializeComponent();
                      base.OnInit(e);
                }

                /// <summary>
                /// Required method for Designer support - do not modify
                /// the contents of this method with the code editor.
                /// </summary>
                private void InitializeComponent()
                {   
                      this.dblExistingCities.SelectedIndexChanged += new System.EventHandle
    (this.dblExistingCities_SelectedIndexChanged);
                      this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
                      this.Load += new System.EventHandler(this.Page_Load);
     
                }
                #endregion

                private void dblExistingCities_SelectedIndexChanged(object sender,
    System.EventArgs e)
                {
                      if ((lblmode.Text=="Edit") || (lblmode.Text=="Delete"))
                      {
                            if (dblExistingCities.Items.Count>0)
                            {
                                  showCityName();
                            }
                      }
                }
                public Boolean CheckValidation()
                {
                      Boolean blnCheck=false;
                      if ((lblmode.Text=="Edit") || (lblmode.Text=="Delete"))
                      {
                            if (dblExistingCities.Items.Count==0)
                            {
                                  lblMessage.Text="No Data to Udate";
                                  blnCheck=true;   
                            }
                      }
                      return blnCheck;
                }
                private void btnSave_Click(object sender, System.EventArgs e)
                {
                      lblMessage.Text="";
                      Boolean blnValidate=CheckValidation();
                if (blnValidate==false)
                      {
                            CityMaster vCM=new CityMaster();
                            if (lblmode.Text=="Add")
                            {
                                  vCM.CityCode=0;
                            }
                            else
                            {
                                  vCM.CityCode=Convert.ToInt32(dblExistingCities.SelectedItem.Value);
                            }
                            vCM.CityName=txtCityName.Text.ToUpper().Trim();
                            IbusinessLogic iBLogic=new CityMasterBO();
                            IBusinessEntity iBEntity=new CityMaster();
                            BusinessService bService=new BusinessService();
                            bService.BusinessEntity=iBEntity;
                            bService.BusinessLogic=iBLogic;
                            bool blnExists=false;
                            blnExists=bService.Execute(OperationType.Exists,vCM);
                            if (lblmode.Text=="Add")
                            {
                                  if (blnExists==false)
                                  {
                                        bService.Execute(OperationType.Create,vCM);
                                        lblMessage.Text="Data Inserted";
                                        dblExistingCities.Items.Clear();
                                        getExistingCityNames();
                                        txtCityName.Text="";
                                  }
                                  else
                                  {
                                        lblMessage.Text="Data already Exists";
                                  }
                            }
                            else if (lblmode.Text=="Edit")
                            {
                                  if (blnExists==true)
                                  {
                                        bService.Execute(OperationType.Update,vCM);
                                        lblMessage.Text="Data Updated";
                                        dblExistingCities.Items.Clear();
                                        getExistingCityNames();
                                        txtCityName.Text="";
                                        if (dblExistingCities.Items.Count>0)
                                        {
                                              showCityName();
                                        }
                                  }
                                  else
                                  {
                                        lblMessage.Text="Data does not exists";
                                  }
     
                            }
                            else if (lblmode.Text=="Delete")
                            {
                                  if (blnExists==true)
                                  {
                                        bService.Execute(OperationType.Delete,vCM);
                                        lblMessage.Text="Data Deleted";
                                        dblExistingCities.Items.Clear();
                                        getExistingCityNames();
                                        txtCityName.Text="";
                                        if (dblExistingCities.Items.Count>0)
                                        {
                                              showCityName();
                                        }
                                  }
                                  else
                                  {
                                        lblMessage.Text="Data does not exists";
                                  }
                            }
                      }
                }
          }
    }


    4. Compile and run the Application.


Similar Articles