BranchAdmin (Model)

  public string branchid { get; set; }
  public IEnumerable<SelectListItem> BranchOptions { get; set; }
   
AdminController (Controller)

   [HttpGet]
        public ActionResult AddBranchAdmin()
        {
            var model = new BranchAdmin ();
            // Populate the dropdown options
            model.BranchOptions = GetBranches("0"); // Set the default to American Express
         
            return View(model);
        }
        private List<SelectListItem> GetBranches(string defaultValue)
        {
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem { Text = "Select", Value = "0", Selected = (defaultValue == "0") });
            SqlCommand cmd = new SqlCommand("select id,branch from Branch", cn);
            cn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                items.Add(new SelectListItem { Text = dr["branch"].ToString(), Value = dr["id"].ToString() });
            }      
            dr.Close();
            cn.Close();

            return items;
        }

AddBranchAdmin (View)

@model CabAutomationSystem.Models.BranchAdmin

  <div class="editor-field">                
                     @Html.DropDownListFor(model => model.branchid, new SelectList(Model.BranchOptions, "Value", "Text"))
                 
                    @Html.ValidationMessageFor(m => m.branch)
                </div>
               
Export to Excel With Multiple sheets using VB.NET


 Private Sub btnexport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnexport.Click
        Try
            Dim dt As New DataTable()
            Dim dtLane As New DataTable
            Dim dtAsset As New DataTable

            Dim filterdate1 As DateTime
            Dim filterdate2 As DateTime
            Dim Container_id As Int64
            Dim facility_lane_idalerts As Int64
            facility_lane_idalerts = -1
            Container_id = -1
            If txtAlertDate.Text <> "" Then
                filterdate1 = Convert.ToDateTime(txtAlertDate.Text)
                filterdate2 = filterdate1.AddDays(1)
            End If
            If ddlAlertContainer.SelectedValue <> "" Then
                Container_id = ddlAlertContainer.SelectedValue
            End If
            If ddlAlertContainer.SelectedValue = 0 Then
                Container_id = -1
            End If
            If ddlAlertLane.SelectedValue <> 0 Then
                facility_lane_idalerts = ddlAlertLane.SelectedValue
            End If
            If txtAlertDate.Text = "" And Container_id = -1 And facility_lane_idalerts = -1 Then
                Dim qry As String = "SELECT OrphanRecord_ID" &
                                ",a.Created_dt" &
                                ",TagNumber" &
                                ",b.door_name" &
                                " FROM OrphansForLaneEntry  a " &
                                " inner join dbo.facility_lane b on a.TReadIP=b.IPReader " &
                                " WHERE  a.Created_dt>DATEADD(DAY,-1,getdate()) and Reason='NO ASSET' and b.facility_ID=" &
                                hdnFacilityID.Value.ToString()
                dtAsset = DataConnect.GetInstance.GetDt(qry)
                qry = "SELECT OrphanRecord_ID" &
                                ",a.Created_dt" &
                                ",TagNumber" &
                            ",b.door_name,con.container_nbr" &
                            " FROM OrphansForLaneEntry  a " &
                            " inner join dbo.facility_lane b on a.TReadIP=b.IPReader " &
                            " left join dbo.container con on a.container_id=con.container_id " &
                                " WHERE  a.Created_dt>DATEADD(DAY,-1,getdate()) and Reason='NO LANE ASSIGNMENT' and b.facility_ID=" &
                                hdnFacilityID.Value.ToString()
                dtLane = DataConnect.GetInstance.GetDt(qry)

         
            End If

            'Create Tempory Table
            Dim dtTemp As New DataTable()
            Dim dtTemp1 As New DataTable()

            'Creating Header Row
            dtTemp.Columns.Add("Created")
            dtTemp.Columns.Add("TagNumber")
            dtTemp.Columns.Add("Door")



            dtTemp1.Columns.Add("Created")
            dtTemp1.Columns.Add("TagNumber")
            dtTemp1.Columns.Add("Door")
            dtTemp1.Columns.Add("Container")

            Dim dtDate As New DateTime
            Dim dtDate1 As New DateTime

            Dim drAddItem As DataRow
            For i As Integer = 0 To dtAsset.Rows.Count - 1
                drAddItem = dtTemp.NewRow()
                dtDate = Convert.ToDateTime(dtAsset.Rows(i)("Created_dt").ToString())
                drAddItem(0) = dtDate
                drAddItem(1) = dtAsset.Rows(i)("TagNumber").ToString()
                drAddItem(2) = dtAsset.Rows(i)("door_name").ToString()
                dtTemp.Rows.Add(drAddItem)
            Next

            Dim drAddItem1 As DataRow
            For i As Integer = 0 To dtLane.Rows.Count - 1
                drAddItem1 = dtTemp1.NewRow()
                dtDate1 = Convert.ToDateTime(dtLane.Rows(i)("Created_dt").ToString())
                drAddItem1(0) = dtDate1
                drAddItem1(1) = dtLane.Rows(i)("TagNumber").ToString()
                drAddItem1(2) = dtLane.Rows(i)("door_name").ToString()
                drAddItem1(3) = dtLane.Rows(i)("container_nbr").ToString()
                dtTemp1.Rows.Add(drAddItem1)
            Next

            'Dim ds As New DataSet
            'ds.Tables.Add(dtTemp)
            'ds.Tables.Add(dtTemp1)
            'Dim dg As New DataGrid
            'dg.DataSource = ds
            'dg.DataBind()
            'ExportToExcel("Alerts.xls", dg)

            Dim rescDS As DataSet = New DataSet
            Dim studiesDS As DataSet = New DataSet
            ' Get data
            rescDS.Tables.Add(dtTemp)
            studiesDS.Tables.Add(dtTemp1)
            ' Create Excel Application, Workbook, and WorkSheets
            Dim xlExcel As New Excel.Application
            Dim xlBooks As Excel.Workbooks
            Dim xlBook As Excel.Workbook
            Dim xlSheets As Excel.Sheets
            Dim stdSheet As Excel.Worksheet
            Dim xlCells As Excel.Range
            Dim sFile As String
            Dim sTemplate As String
            Dim rescSheet As Excel.Worksheet

            sFile = Server.MapPath("ExcelFormatFile\LaneAssignmentAlerts.xls")
            ' Formatted template the way you want.
            ' If you want to change the format, change this template
            sTemplate = Server.MapPath("\ExcelFormatFile\LaneAssignment.xls")
            xlExcel.Visible = False : xlExcel.DisplayAlerts = False
            ' Get all workbooks and open first workbook
            xlBooks = xlExcel.Workbooks
            xlBooks.Open(Server.MapPath("\ExcelFormatFile\LaneAssignment.xls"))
            xlBook = xlBooks.Item(1)
            ' Get all sheets available in first book
            xlSheets = xlBook.Worksheets
            ' Get first sheet, change its name and get all cells
            stdSheet = CType(xlSheets.Item(1), Excel.Worksheet)
            stdSheet.Name = "Unidentified Lane Assignment"
            xlCells = stdSheet.Cells
            ' Fill all cells with data
            GenerateExcelFile(studiesDS.Tables(0), xlCells) 'Fill in the data

            ' Get second sheet, change its name and get all cells
            rescSheet = CType(xlSheets.Item(2), Excel.Worksheet)
            rescSheet.Name = "Unidentified Asset Movement"
            xlCells = rescSheet.Cells
            ' Fill all cells with data
            GenerateExcelFile(rescDS.Tables(0), xlCells)

            ' Save created sheets as a file
            xlBook.SaveAs(sFile)

            ' Make sure all objects are disposed
            xlBook.Close()
            xlExcel.Quit()
            ReleaseComObject(xlCells)
            ReleaseComObject(stdSheet)
            ReleaseComObject(xlSheets)
            ReleaseComObject(xlBook)
            ReleaseComObject(xlBooks)
            ReleaseComObject(xlExcel)
            xlExcel = Nothing
            xlBooks = Nothing
            xlBook = Nothing
            xlSheets = Nothing
            stdSheet = Nothing
            xlCells = Nothing
            rescSheet = Nothing
            ' Let GC know about it
            GC.Collect()

            ' Export Excel for download
            Dim File As FileInfo = New FileInfo(sFile)
            Response.Clear()
            Response.Charset = "UTF-8"
            Response.ContentEncoding = System.Text.Encoding.UTF8
            'Add header, give a default file name for "File Download/Store as"
            Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(File.Name))
            'Add header, set file size to enable browser display download progress
            Response.AddHeader("Content-Length", File.Length.ToString())
            'Set the return string is unavailable reading for client, and must be downloaded
            Response.ContentType = "application/ms-excel"
            'Send file string to client
            Response.TransmitFile(File.FullName)

            Response.End()
        Catch ex As Exception
            pnlGlobalMessage.Visible = True
            lblGlobalMessage.Text = "A technical issue has occurred.  A message has been sent to the development team.  Sorry for the inconvenience."
            lblGlobalMessage.Visible = True
            Dim dt As DataTable = Session("user_session")
            Worker.HandleError(ex, "Lane History Excel", Int64.Parse(dt.Rows(0)("user_id")), Request.Browser.Browser.ToString())
        End Try
    End Sub

    ' Generates Excel sheet for the given DataTable's data
    Private Function GenerateExcelFile(ByRef table As DataTable, ByVal xlCells As Excel.Range) As String
        Dim dr As DataRow, ary() As Object
        Dim iRow As Integer, iCol As Integer
        'Output Column Headers
        For iCol = 0 To table.Columns.Count - 1
            xlCells(1, iCol + 1) = table.Columns(iCol).ToString
        Next
        'Output Data
        For iRow = 0 To table.Rows.Count - 1
            dr = table.Rows.Item(iRow)
            ary = dr.ItemArray
            For iCol = 0 To UBound(ary)
                xlCells(iRow + 2, iCol + 1) = ary(iCol).ToString
                Response.Write(ary(iCol).ToString & vbTab)
            Next
        Next
    End Function

Private Sub btnOk_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOk.Click
        Try
            Dim Stream As MemoryStream = pdf()
            Response.Clear()
            Response.AddHeader("content-type", "application/pdf")
            Response.AddHeader("cache-control", "no-cache")
            Response.AddHeader("accept-ranges", "none")
            Dim filename As String = "BOLDetails_" & Request.QueryString("ID").ToString() & ".pdf"
            saveFile(Stream, filename)
            Response.AddHeader("content-disposition", "attachment; filename=" & filename)
            Response.OutputStream.Write(Stream.GetBuffer(), 0, Stream.GetBuffer().Length)
            Response.OutputStream.Flush()
            'Response.Write("<script type='text/javascript'>window.close();</script>")
            Response.OutputStream.Close()
            Response.End()
            'Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "close", "<script type='text/javascript'>window.close();</script>")
        Catch ex As Exception
            Response.Write(ex.Message.ToString())
        End Try
    End Sub


 Private Function pdf() As MemoryStream
        Dim content As String = createHTML()
        Dim reader As TextReader = New StringReader(content)
        Dim doc As New Document(iTextSharp.text.PageSize.A4, 10, 10, 10, 10)
        Dim Stream As New MemoryStream()
        Dim wri As PdfWriter
        wri = PdfWriter.GetInstance(doc, Stream)
        doc.Open()
        Dim htmlarraylist As List(Of IElement) = html.simpleparser.HTMLWorker.ParseToList(reader, Nothing)
        For k As Integer = 0 To htmlarraylist.Count - 1
            doc.Add(DirectCast(htmlarraylist(k), IElement))
        Next
        doc.Close()
        Return Stream
    End Function

    Protected Function createHTML() As String
        Dim html As String = "<table cellspacing='0' cellpadding='0' border='0'><tbody>"
        If chkCreatedDate.Checked = True Then
            html = html & "<tr>" &
                "<td valign='top' align='left'>" &
                "Created Date:" &
                "</td>" &
                "<td valign='top' align='left'>" &
                txtCreatedDate.Text &
                "</td>" &
                "</tr>"
        End If
        If chkClearDate.Checked = True Then
            html = html & "<tr>" &
                "<td valign='top' align='left'>" &
                "Clear Date:" &
                "</td>" &
                "<td valign='top' align='left'>" &
                txtClearDate.Text &
                "</td>" &
                "</tr>"
        End If
        If chkDoor.Checked = True Then
            html = html &
                "<tr>" &
                "<td valign='top' align='left'>" &
                "Door #:" &
                "</td>" &
                "<td valign='top' align='left'>" &
                txtDoor.Text &
                "</td>" &
                "</tr>"
        End If
        If chkName.Checked = True Then
            html = html &
                "<tr>" &
                "<td valign='top' align='left'>" &
                "Name:" &
                "</td>" &
                "<td valign='top' align='left'>" &
                txtName.Text &
                "</td>" &
                "</tr>"
        End If
        If chkDirection.Checked = True Then
            html = html &
                    "<tr>" &
                    "<td valign='top' align='left'>" &
                    "Direction:" &
                    "</td>" &
                    "<td valign='top' align='left'>" &
                    txtDirection.Text &
                    "</td>" &
                    "</tr>"
        End If
        If chkTrailer.Checked = True Then
            html = html &
                    "<tr>" &
                    "<td valign='top' align='left'>" &
                    "Trailer:" &
                    "</td>" &
                    "<td valign='top' align='left'>" &
                    txtTrailer.Text &
                    "</td>" &
                    "</tr>"
        End If
        If chkCarrier.Checked = True Then
            html = html &
                    "<tr>" &
                    "<td valign='top' align='left'>" &
                    "Carrier:" &
                    "</td>" &
                    "<td valign='top' align='left'>" &
                    txtCarrier.Text &
                    "</td>" &
                    "</tr>"
        End If
        If chkToFrom.Checked = True Then
            html = html &
                    "<tr>" &
                    "<td valign='top' align='left'>" &
                    "To/From:" &
                    "</td>" &
                    "<td valign='top' align='left'>" &
                    txtToFrom.Text &
                    "</td>" &
                    "</tr>"
        End If
        If chkCompany.Checked = True Then
            html = html &
                    "<tr>" &
                    "<td valign='top' align='left'>" &
                    "Company:" &
                    "</td>" &
                    "<td valign='top' align='left'>" &
                    txtCompany.Text &
                    "</td>" &
                    "</tr>"
        End If
        If chkCompanyLoc.Checked = True Then
            html = html &
                    "<tr>" &
                    "<td valign='top' align='left'>" &
                    "Company Location:" &
                    "</td>" &
                    "<td valign='top' align='left'>" &
                    txtCompanyLoc.Text &
                    "</td>" &
                    "</tr>"
        End If
        html = html & "</tbody></table>"
        Return html
    End Function

Staff (Model)


       public string branchid { get; set; }
        public IEnumerable<SelectListItem> BranchOptions { get; set; }

        public string countryid { get; set; }
        public IEnumerable<SelectListItem> CountryOptions { get; set; }

     
        public IEnumerable<SelectListItem> DepartmentOptions { get; set; }

AdminController (Controller)


  public enum Departments { All, Marketing, Front, Councellor, Application, Documentation, Accounts, Franchisee, Employer,Agency,Institution,Training }
        [HttpGet]
        public ActionResult AddStaff()
        {
            var model = new Staff();
            model.DepartmentOptions = Enum.GetNames(typeof(Departments))
            .Select(c => new SelectListItem() { Text = c, Value = c })
            .ToArray();

            model.CountryOptions = GetCountries("0");
            model.BranchOptions = GetBranches ("0");

            return View(model);
        }
        private List<SelectListItem> GetCountries(string defaultValue)
        {
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem { Text = "Select", Value = "0", Selected = (defaultValue == "0") });
            SqlCommand cmd = new SqlCommand("select id,cntry from cntry", cn);
            cn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                items.Add(new SelectListItem { Text = dr["cntry"].ToString(), Value = dr["id"].ToString() });
            }
            dr.Close();
            cn.Close();

            return items;
        }


  private List<SelectListItem> GetBranches(string defaultValue)
        {
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem { Text = "Select", Value = "0", Selected = (defaultValue == "0") });
            SqlCommand cmd = new SqlCommand("select id,branch from Branch", cn);
            cn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                items.Add(new SelectListItem { Text = dr["branch"].ToString(), Value = dr["id"].ToString() });
            }      
            dr.Close();
            cn.Close();

            return items;
        }


AddStaff (View)


@model CabAutomationSystem.Models.Staff

@{            
    ViewBag.Title = "AddStaff";
    Layout = "~/Views/Admin/Master.cshtml";
}


<body>
<h1>Add New Staff</h1>
    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true, "Insertion was unsuccessful. Please correct the errors and try again.")
        <div>
            <fieldset>
                <legend>Staff Information</legend>
             
                <div class="editor-label">
                    @Html.LabelFor(m => m.department)
                </div>
                <div class="editor-field">                
                     @Html.DropDownListFor(model => model.department, new SelectList(Model.DepartmentOptions, "Value", "Text"))
                 
                    @Html.ValidationMessageFor(m => m.department)
                </div>
             
                <div class="editor-label">
                    @Html.LabelFor(m => m.uname)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.uname)
                    @Html.ValidationMessageFor(m => m.uname)
                </div>
             
                <div class="editor-label">
                    @Html.LabelFor(m => m.pwd)
                </div>
                <div class="editor-field">
                    @Html.PasswordFor(m => m.pwd)
                    @Html.ValidationMessageFor(m => m.pwd)
                </div>

                 <div class="editor-label">
                    @Html.LabelFor(m => m.name)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.name)
                    @Html.ValidationMessageFor(m => m.name)
                </div>

                 <div class="editor-label">
                    @Html.LabelFor(m => m.address)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.address)
                    @Html.ValidationMessageFor(m => m.address)
                </div>

                 <div class="editor-label">
                    @Html.LabelFor(m => m.phoneno)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.phoneno)
                    @Html.ValidationMessageFor(m => m.phoneno)
                </div>

                 <div class="editor-label">
                    @Html.LabelFor(m => m.email)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.email)
                    @Html.ValidationMessageFor(m => m.email)
                </div>

                  <div class="editor-label">
                    @Html.LabelFor(m => m.country)
                </div>
                <div class="editor-field">                
                     @Html.DropDownListFor(model => model.countryid, new SelectList(Model.CountryOptions, "Value", "Text"))
                 
                    @Html.ValidationMessageFor(m => m.countryid)
                </div>

                  <div class="editor-label">
                    @Html.LabelFor(m => m.branch)
                </div>
                <div class="editor-field">                
                     @Html.DropDownListFor(model => model.branchid, new SelectList(Model.BranchOptions, "Value", "Text"))
                 
                    @Html.ValidationMessageFor(m => m.branchid)
                </div>
                           
                <p>
                    <input type="submit" value="Insert" />
                </p>
            </fieldset>
        </div>
    }
</body>

HomeController.cs (Controller)


  [HttpGet]
        public ActionResult Admin()
        {
            //ViewBag.Message = "Welcome to Login Page";
            //var v = ViewData.Model = _db.Employee.ToList();
            // return View(v);
            return View();
        }
        [HttpPost]
        public ActionResult Admin(CabAutomationSystem.Models.LoginModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.IsValid(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

                    return RedirectToAction("Home", "Admin");

                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }


            return View(model);
        }

LoginModel.cs (Model)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Net.Mail;

namespace CabAutomationSystem.Models
{
    public class LoginModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }
        public bool IsValid(string _username, string _pwd)
        {
            string _sql = "Select uname From Login Where uname='" + _username + "' And pwd='" + _pwd + "'";
            SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SLMFConnection"].ToString());
            cn.Open();
            SqlCommand cmd = new SqlCommand(_sql, cn);
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
                return true;
            else
                return false;

        }

    }
}

Admin.cshtml (View)


@model CabAutomationSystem.Models.LoginModel
           @{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title></title>
    <link href="@Url.Content("~/Content/admin_style.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/Mystyle.css")" rel="stylesheet" type="text/css" />  
    <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
</head>
<body>
    <div>
    <div>
 
 
    <div id="OuterContainer">
<div id="LogoContainer"></div>
</div>
<div id="HeaderContainer">
 
   
 
</div>

   <div id="BannerContainer">
        <div id="BannerArea">
                &nbsp;</div>
      </div>
     
        <div id="MenuContainer">
        <div id="MenuArea">
            <div id="Menu" >
              </div>
            </div>
        </div>
     
        <div id="ConetntAreaContainer" class="clear">
        <div id="CategoryContainer" style="height:100px">
         <div style="clear:both">
                    <a href="@Url.Action("Default", "Shared")" title="Branch">
                                            <img src="../../Content/images/back.jpg" />
                                           </a>
                 
                      </div>
          </div>
             
                <div id="ContentContainer" style="width:98%">
                 <div id="Welcomecontent">
                   <p>
                      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
         <table align="center" border="0" cellpadding="0" cellspacing="0" width="300">
             <tr>
                 <td valign="top" width="16">
                     <img alt="" height="14" src="../../Content/images/whitebox_01.jpg" width="16" /></td>
                 <td background="../../Content/images/whitebox-topbg.jpg" valign="top">
                     <img height="14" src="../../Content/images/whitebox-topbg.jpg" width="1" /></td>
                 <td valign="top" width="19">
                     <img alt="" height="14" src="../../Content/images/whitebox_03.jpg" width="19" /></td>
             </tr>
             <tr>
                 <td background="../../Content/images/whitebox-left-bg.jpg" height="56" valign="top">&nbsp;
                </td>
                 <td valign="top">
                 @Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
                 @using (Html.BeginForm())
                 {
                     <table align="center" bgcolor="#0066CC" cellpadding="2" cellspacing="2"
                         width="300">
                         <tr>
                             <td colspan="2" height="35" style="font-size: 14px; color: #006600;
                                 text-align: left">
                                 <strong class="adminhead">Administrator Login</strong></td>
                         </tr>
                         <tr>
                             <td align="right" class="style1" >
                                 <strong> @Html.LabelFor(m => m.UserName)</strong></td>
                             <td class="admin_txt" style="text-align: left">
                                @Html.TextBoxFor(m => m.UserName)
                @Html.ValidationMessageFor(m => m.UserName)
                </td>
                         </tr>
                         <tr>
                             <td align="right" class="style1" >
                                 <strong>@Html.LabelFor(m => m.Password)</strong></td>
                             <td class="admin_txt" style="text-align: left">
                         @Html.PasswordFor(m => m.Password)
                @Html.ValidationMessageFor(m => m.Password)
                                     </td>
                         </tr>
                         <tr>
                             <td class="admin_txt" style="width: 100px; text-align: left">                             </td>
                             <td class="admin_txt">
                              @Html.CheckBoxFor(m => m.RememberMe)
                @Html.LabelFor(m => m.RememberMe)
                           </td>
                         </tr>
                         <tr>
                             <td>                             </td>
                             <td class="style2" style="text-align: center">
                           <input type="submit" value="Login" />
                               
                           </td>
                         </tr>
                   </table>
                 }
                 </td>
                 <td background="../../Content/images/whitebox-right-bg.jpg" valign="top">
                     <img height="1" src="../../Content/images/whitebox-right-bg.jpg" width="19" /></td>
             </tr>
             <tr>
                 <td valign="top">
                     <img alt="" height="18" src="../../Content/images/whitebox_07.jpg" width="16" /></td>
                 <td background="../../Content/images/whitebox-bottom-bg.jpg" valign="top">
                     <img height="18" src="../../Content/images/whitebox-bottom-bg.jpg" width="1" /></td>
                 <td valign="top">
                     <img alt="" height="18" src="../../Content/images/whitebox_09.jpg" width="19" /></td>
             </tr>
         </table>
<br />
                    </p>
                    </div>
                 
          </div>
                <div style="clear:both"></div>
        </div>
     
   
     
     <div id="FooterConatiner" style="height:25px"></div>
   </div>
   
    </div>
</body>
</html>


 <input id="filePathHidden" runat="server"  type="hidden" />
        <asp:FileUpload ID="FileUpload1" runat="server" />
   
        <asp:Button ID="Button1" runat="server"
            Text="Button" onclick="Button1_Click" />
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Aspose.Cells;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string path = Server.MapPath(FileUpload1.FileName);
        Workbook workbook = new Workbook();      
        workbook.Open(FileUpload1.PostedFile.InputStream);
        //Get the first worksheet cells collection
        Cells cells = workbook.Worksheets[0].Cells;

        for (int i = 1; i < cells.MaxDataRow; i++)
        {
            for (int j = 0; j < cells.MaxDataColumn; j++)
            {
                Response.Write(cells[i, j].StringValue);

            }
        }
        System.Data.DataTable dt = new DataTable();
     
        dt = cells.ExportDataTable(1, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1);
        dt.Columns[0].ColumnName = "Question";
        dt.Columns[1].ColumnName = "Choice1";
        dt.Columns[2].ColumnName = "Choice2";
        dt.Columns[3].ColumnName = "Choice3";
        dt.Columns[4].ColumnName = "Choice4";
        dt.Columns[5].ColumnName = "Answer";
        dt.AcceptChanges();
        GridView1.DataSource = dt;
        GridView1.DataBind();
     
    }
}
MVC Tutorials
·         Models: Model objects are the parts of the application that implement the domain logic. Often, model objects also retrieve and store model state in a database.
·         Views: Views are the components that display the application's user interface (UI). Typically, this UI is created from the model data. An example would be the edit view of Albums that displays text boxes and a drop-down list based on the current state of an Album object.
·         Controllers: Controllers are the components that handle user interaction, manipulate the model, and ultimately select a view to render the UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction.

Start page setting in _ViewStart.cshtml in Views folder
@{
// Set the layout page for the whole site
Layout = "~/Shared/Layout.cshtml";
}
Eg:- @{
    Layout = "~/Views/Shared/Index.cshtml";
    }
1.       Main Folders
·         Controllers- for storing controllers
·         Models-for storing models
·         Views-for storing views
·         App_Data - for storing databases and data files
·         Content/Images - for storing images
·         Scripts - for storing browser scripts
·         Views/Shared - for storing shared style and layout files

2.    Database Connection and management in Models
  Creating the Model
On the Models folder, right click and create a new class by clicking on Add -> Class.
Example:-
                                    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel.DataAnnotations;
using connectionClass;

namespace CabAutomationSystem.Models
{
    public class Country
    {
        connectionClass.connectionClass cs = new connectionClass.connectionClass();
        public string conStr = ConfigurationManager.ConnectionStrings["SLMFConnection"].ToString();
        SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SLMFConnection"].ToString());

        public int id { get; set; }
        [Required(ErrorMessage = "Country is required")]
        [Display(Name = "Country:")]
        public string country { get; set; }

        public DataSet GetAllCountry()
        {
            SqlCommand cmd = new SqlCommand("select id,cntry from cntry order by id", cn);
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            return ds;
        }


        public int Insert(string country)
        {
            Int64 id = cs.GenerateId("cntry", "id", conStr);
            SqlCommand cmd = new SqlCommand("insert into cntry(id,cntry) values('" + id + "','" + country + "')", cn);
            cn.Open();        
            return cmd.ExecuteNonQuery();
        }

        public int Update(string country,  int id)
        {
            SqlCommand cmd = new SqlCommand("Update cntry Set cntry='" + country + "' Where id=" + id, cn);
            cn.Open();        
            return cmd.ExecuteNonQuery();
        }
        public int Delete(int id)
        {
            SqlCommand cmd = new SqlCommand("Delete From cntry Where id=" + id, cn);
            cn.Open();
            return cmd.ExecuteNonQuery();
        }
    }
}

3.    User interaction management and model manipulation in Controllers
            Creating our Controller
                   Right click on the Controllers folder and select Add -> Controller.    
Example:-
                                    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CabAutomationSystem.Models;
using CabAutomationSystem.DatabaseContext;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel.DataAnnotations;
using connectionClass;

namespace CabAutomationSystem.Controllers
{
    public class AdminController : Controller
    {
        connectionClass.connectionClass cs = new connectionClass.connectionClass();
        public string conStr = ConfigurationManager.ConnectionStrings["SLMFConnection"].ToString();
        SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SLMFConnection"].ToString());

#region ManageCountry
        public ActionResult ManageCountry(CabAutomationSystem.Models.Country CountryList)
        {
            DataSet ds = CountryList.GetAllCountry();
            ViewBag.AuthorList = ds.Tables[0];
            return View();
        }    
        [HttpGet]
        public ActionResult AddCountry()
        {
            return View();
        }
        [HttpPost]
        public ActionResult AddCountry(CabAutomationSystem.Models.Country countryinsert)
        {
            if (ModelState.IsValid)
            {
                int _records = countryinsert.Insert(countryinsert.country);
                if (_records > 0)
                {
                    return RedirectToAction("ManageCountry", "Admin");
                }
                else
                {
                    ModelState.AddModelError("", "Can Not Insert");
                }

            }
            return View(countryinsert);
        }
        [HttpGet]
        public ActionResult EditCountry(int id, CabAutomationSystem.Models.Country countryupdate)
        {
            SqlCommand cmd = new SqlCommand("select id,cntry from cntry where id=" + id, cn);
            cn.Open();
            SqlDataReader dr = cmd.ExecuteReader();

            if (dr.Read())
            {
                countryupdate.id = Convert.ToInt32(dr["id"].ToString());
                countryupdate.country = dr["cntry"].ToString();
            }
            else
            {
                dr.Close();
            }
            dr.Close();
            cn.Close();

            return View(countryupdate);
        }
        [HttpPost]
        public ActionResult EditCountry(CabAutomationSystem.Models.Country countryupdate, FormCollection form, int id)
        {

            if (ModelState.IsValid)
            {
                int _records = countryupdate.Update(countryupdate.country, id);
                if (_records > 0)
                {
                    return RedirectToAction("ManageCountry", "Admin");
                }
                else
                {
                    ModelState.AddModelError("", "Can Not Update");
                }
            }
            return View(countryupdate);
        }
        public ActionResult DeleteCountry(int id, CabAutomationSystem.Models.Country countrydelete)
        {
            int records = countrydelete.Delete(id);
            if (records > 0)
            {
                return RedirectToAction("ManageCountry", "Admin");
            }
            else
            {
                ModelState.AddModelError("", "Can Not Delete");
                return View("ManageCountry");
            }
            // return View("Index");
        }
        #endregion ManageCountry
}
}
4.    User Interface Management in Views
Example:-
v  Right click on  “ManageCountry” in Controller and create view “ManageCountry.cshtml”
              @model CabAutomationSystem.Models.Country
   
@{
    ViewBag.Title = "ManageCountry";
    Layout = "~/Views/Admin/Master.cshtml";
}

<h2>ManageCountry</h2>

 <div>
       @Html.ActionLink("Add Country", "AddCountry")
       <br />
      <table border="1" style="border-color:LightSkyBlue;border-bottom-style:double">
      <tr>
<td></td>
<td></td>
<td style="background-color: #800080; color: #FFFFFF; font-family: 'Times New Roman', Times, serif;
     font-size: large; border-style: inset; border-width: thin">Country</td>
      </tr>
        @foreach (System.Data.DataRow dr in ViewBag.AuthorList.Rows)
          {
          <tr>
          <td>
                @Html.ActionLink("Edit", "EditCountry", new { id = dr["id"].ToString() })
          </td>
          <td>
                @Html.ActionLink("Delete", "DeleteCountry", new { id = dr["id"].ToString() })
           </td>
           <td>
                @dr["cntry"].ToString()
           </td>
   
         </tr>
       }
       </table>
   
 
    </div>

v  Right click on  “AddCountry” in Controller and create view “AddCountry.cshtml”

@model CabAutomationSystem.Models.Country

@{
    ViewBag.Title = "AddCountry";
    Layout = "~/Views/Admin/Master.cshtml";
}


<body>
<h1>Add New Country</h1>
    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true, "Insertion was unsuccessful. Please correct the errors and try again.")
        <div>
            <fieldset>
                <legend>Country Information</legend>
             
                <div class="editor-label">
                    @Html.LabelFor(m => m.country)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.country)
                    @Html.ValidationMessageFor(m => m.country)
                </div>
                         
                             
                <p>
                    <input type="submit" value="Insert" />
                </p>
            </fieldset>
        </div>
    }
</body>

v  Right click on  “EditCountry” in Controller and create view “EditCountry.cshtml”

@model CabAutomationSystem.Models.Country

@{
    ViewBag.Title = "EditCountry";
    Layout = "~/Views/Admin/Master.cshtml";
}


<body>
<h1>Edit Country</h1>
    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true, "Insertion was unsuccessful. Please correct the errors and try again.")
        <div>
            <fieldset>
                <legend>Country Information</legend>
             
                <div class="editor-label">
                    @Html.LabelFor(m => m.country)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.country)
                    @Html.ValidationMessageFor(m => m.country)
                </div>
                         
                           
                <p>
                    <input type="submit" value="Update" />
                </p>
            </fieldset>
        </div>
    }
</body>

5.  Master.cshtml in Views



<!DOCTYPE html>

<html>
<head>
    <title></title>
    <link href="@Url.Content("~/Content/admin_style.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/Mystyle.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
</head>
<body>
   <div class="top">
              <div class=""></div>
              <div class="contact">
              <p>
           
                           </p>
              </div>
       </div>
 

       <input id="hdndranch" runat="server" type="hidden" />
    <div>
     <div>    
     
        <div id="ConetntAreaContainer" class="clear">
            <table style="width: 100%" width="100%">
                <tr>
                    <td style="width: 20%" valign="top">
                      <table cellpadding="6" cellspacing="3" width="100%" style="background-color: #996633">
                          <tr>
                              <td style="width: 8px">
                              </td>
                              <td height="10">
                              </td>
                          </tr>
                          <tr >
                              <td style="width: 8px">
                                  <img src="../../Content/images/arrow_doublebl.jpg" /></td>
                              <td>
                                @*@Html.ActionLink("Home", "Home", "Admin", new { @class = "ad_link" })*@
                                @Html.ActionLink("Home", "Home", "Admin")
                                </td>
                          </tr>
                            <tr id="tr3" runat="server">
                              <td style="width: 8px">
                                  <img src="../../Content/images/arrow_doublebl.jpg" /></td>
                              <td>
                              @Html.ActionLink("ManageCountry", "ManageCountry", "Admin")
                           
                                      </td>
                          </tr>                  
                       

                          <tr id="tr49" runat="server">
                              <td style="width: 8px">
                                  <img src="../../Content/images/arrow_doublebl.jpg" /></td>
                              <td>
                                @Html.ActionLink("Logout", "Logout", "Admin", new { @class = "ad_link" })
                           
                                      </td>
                          </tr>
                      </table>
                    </td>
                    <td style="width: 80%" valign="top">
             
                <div id="ContentContainer" style="width:75%">
                       <div id="Welcomecontent">
                         <p>
                     <br />
     @RenderBody()
   
<br />
                    </p>
                    </div>
                 
          </div>
                    </td>
                </tr>
            </table>
                <div style="clear:both"></div>
        </div>
     
 
     
     <div id="FooterConatiner" style="height:25px"></div>
   </div>
    </div>



</body>
</html>