Tuesday, 29 January 2019

Web service call time given SSL error in ASP .net

<!-- User Validation API at LOGIN module Begin-->
   <system.serviceModel>
  <bindings>
      <basicHttpBinding>
        <binding name="UserValidateSoap">
          <security mode="Transport">
            <transport clientCredentialType="None" />
          </security>
        </binding>
        </basicHttpBinding>
    </bindings>
   <client>
     <endpoint address="https://localhost/abcd.asmx" binding="basicHttpBinding" bindingConfiguration="UserValidateSoap" contract="UserValidate.UserValidateSoap" name="UserValidateSoap" />
   </client>
 </system.serviceModel>
<!--  User Validation API at LOGIN module End-->

Monday, 28 January 2019

Business Logic for Email send mail in C sharp in .net

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Collections;

namespace Business_Logic
{
    public class AppHandler
    {
        private MailAddress emailRecipient;
        private MailAddress emailRecipientCC;
        private MailAddress emailSender;
        private String emailTo;
        private String emailCopy;
        private String emailPriority;
        private String emailSubject;
        private String emailMessage;
        private String emailSmtp;
        private FileUpload[] emailfileUpload;
        private string[] emailFile;
        string[] arrFields = new string[1000];
        string[] arrValues = new string[1000];


        // Email To multiple
        public String EmailTo
        {
            get { return emailTo; }
            set { emailTo = value; }
        }
        // Email Receipient
        public MailAddress EmailRecipient
        {
            get { return emailRecipient; }
            set { emailRecipient = value; }
        }
        // Email Receipient CC
        public MailAddress EmailRecipientCC
        {
            get { return emailRecipientCC; }
            set { emailRecipientCC = value; }
        }
        // Files upload
        public FileUpload[] UploadFiles
        {
            get { return emailfileUpload; }
            set { emailfileUpload = value; }
        }
        public string[] AttachedFilePath
        {
            get { return emailFile; }
            set { emailFile = value; }
        }
       
        //Email sender
        public MailAddress EmailSender
        {
            get { return emailSender; }
            set { emailSender = value; }
        }
       
        // Email copy
        public String EmailCopy
        {
            get { return emailCopy; }
            set { emailCopy = value; }
        }
        // Email Priority
        public String EmailPriority
        {
            get { return emailPriority; }
            set { emailPriority = value; }
        }
        //Email Subject
        public String EmailSubject
        {
            get { return emailSubject; }
            set { emailSubject = value; }
        }
        //Email Message
        public String EmailMessage
        {
            get { return emailMessage; }
            set { emailMessage = value; }
        }

        //Email Smtp address
        public String EmailSmtp
        {
            get { return emailSmtp; }
            set { emailSmtp = value; }
        }
    }
}
========================
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace Business_Logic
{
    public sealed class EmailHandler
    {
        private static char[] charSeparators = new char[] { };
        private static String[] result;
        private static String[] resultCC;
        public static void SendMailMessage(AppHandler pMailApp)
        {
            try
            {
                MailMessage mailMsg = new MailMessage();
                result = pMailApp.EmailRecipient.ToString().Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
                for (int count = 0; count < result.Length; count++)
                {
                    mailMsg.To.Add(new MailAddress(result[count]));
                }
                if (pMailApp.EmailRecipientCC != null)
                {
                    if (!string.IsNullOrEmpty(pMailApp.EmailRecipientCC.ToString()))
                    {
                        resultCC = pMailApp.EmailRecipientCC.ToString().Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
                        for (int count = 0; count < resultCC.Length; count++)
                        {
                            mailMsg.CC.Add(new MailAddress(resultCC[count]));
                        }
                    }
                }
                mailMsg.IsBodyHtml = true;
                //Email Sender
                mailMsg.From = pMailApp.EmailSender;
                //Email Subject
                mailMsg.Subject = pMailApp.EmailSubject;
                //Email Body
                mailMsg.Body = pMailApp.EmailMessage;
                //Email Priority
                switch (pMailApp.EmailPriority.ToString())
                {
                    case "Low" :
                    mailMsg.Priority = MailPriority.Low;
                    break;
                    case "Normal" :
                    mailMsg.Priority = MailPriority.Normal;
                    break;
                    case "High" :
                    mailMsg.Priority = MailPriority.High;
                    break;
                }
                //Attachments
                if (pMailApp.AttachedFilePath != null)
                {
                    for (int i = 0; i < pMailApp.AttachedFilePath.Length; i++)
                    {
                        Attachment attachFile= new Attachment(pMailApp.AttachedFilePath[i]);
                        mailMsg.Attachments.Add(attachFile);            
                    }
                }
                //SMTP address
                SmtpClient smtpClient = new SmtpClient(pMailApp.EmailSmtp);
               // smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpClient.Send(mailMsg);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
        public static void SendMailMessagenewMultiple(AppHandler pMailApp)
        {
            try
            {
                MailMessage mailMsg = new MailMessage();
                result = pMailApp.EmailTo.ToString().Split(';');
                for (int count = 0; count < result.Length; count++)
                {
                    mailMsg.To.Add(new MailAddress(result[count]));
                }
                if (pMailApp.EmailRecipientCC != null)
                {
                    if (!string.IsNullOrEmpty(pMailApp.EmailRecipientCC.ToString()))
                    {
                        resultCC = pMailApp.EmailRecipientCC.ToString().Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
                        for (int count = 0; count < resultCC.Length; count++)
                        {
                            mailMsg.CC.Add(new MailAddress(resultCC[count]));
                        }
                    }
                }
                mailMsg.IsBodyHtml = true;
                //Email Sender
                mailMsg.From = pMailApp.EmailSender;
                //Email Subject
                mailMsg.Subject = pMailApp.EmailSubject;
                //Email Body
                mailMsg.Body = pMailApp.EmailMessage;
                //Email Priority
                switch (pMailApp.EmailPriority.ToString())
                {
                    case "Low":
                        mailMsg.Priority = MailPriority.Low;
                        break;
                    case "Normal":
                        mailMsg.Priority = MailPriority.Normal;
                        break;
                    case "High":
                        mailMsg.Priority = MailPriority.High;
                        break;
                }
                //Attachments
                if (pMailApp.AttachedFilePath != null)
                {
                    for (int i = 0; i < pMailApp.AttachedFilePath.Length; i++)
                    {
                        Attachment attachFile = new Attachment(pMailApp.AttachedFilePath[i]);
                        mailMsg.Attachments.Add(attachFile);
                    }
                }
                //SMTP address
                SmtpClient smtpClient = new SmtpClient(pMailApp.EmailSmtp);
                // smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpClient.Send(mailMsg);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
    }
}

Wednesday, 16 January 2019

Insert, Update, Delete in List view XML in Asp.net c sharp

==========================Employee.xml=========
<?xml version="1.0" encoding="utf-8"?>
<NewElement>
  <Employee>
    <ID>1</ID>
    <Name>pramod s r</Name>
  </Employee>
  <Employee>
    <ID>2</ID>
    <Name>koli</Name>
  </Employee>
  <Employee>
    <ID>3</ID>
    <Name>xyz</Name>
  </Employee>
  <Employee>
    <ID>4</ID>
    <Name>sdfsdf</Name>
  </Employee>
</NewElement>
==============================Design=============================
<asp:ListView ID="lvEmployee" runat="server" InsertItemPosition="LastItem" OnItemInserting="lvEmployee_ItemInserting"
            OnItemDeleting="lvEmployee_ItemDeleting" OnItemEditing="lvEmployee_ItemEditing"
            OnItemCanceling="lvEmployee_ItemCanceling" >
            <LayoutTemplate>
                <table id="Table1" runat="server">
                    <tr id="Tr1" runat="server">
                        <td id="Td1" runat="server">
                            <table id="itemPlaceholderContainer" runat="server" border="0" style="">
                                <tr id="Tr2" runat="server" style="">
                                    <th id="Th1" runat="server">
                                    </th>
                                    <th id="Th2" runat="server">
                                        ID
                                    </th>
                                    <th id="Th3" runat="server">
                                        Name
                                    </th>
                                </tr>
                                <tr id="itemPlaceholder" runat="server">
                                </tr>
                            </table>
                        </td>
                    </tr>
                    <tr id="Tr3" runat="server">
                        <td id="Td2" runat="server" style="">
                        </td>
                    </tr>
                </table>
            </LayoutTemplate>
            <ItemTemplate>
                <tr style="">
                    <td>
                        <asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" />
                        <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
                    </td>
                    <td>
                        <asp:Label ID="lblID" runat="server" Text='<%# Bind("ID") %>' />
                    </td>
                    <td>
                        <asp:Label ID="lblName" runat="server" Text='<%# Bind("Name") %>' />
                    </td>
                </tr>
            </ItemTemplate>
            <InsertItemTemplate>
                <tr style="">
                    <td>
                        <asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" />
                        <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Clear" />
                    </td>
                    <td>
                       
                    </td>
                    <td>
                        <asp:TextBox ID="txtID" runat="server" Text='<%# Bind("ID") %>' />
                    </td>
                    <td>
                        <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name") %>' />
                    </td>
                    <td>
                        <asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click" />
                    </td>
                </tr>
            </InsertItemTemplate>
        </asp:ListView>
==================================Code======================
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Xml;

public partial class Listview_XML : System.Web.UI.Page
{
    //Global varaiable declaration
    string xmlfile = @"E:\Employee.xml";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadData();
        }

    }
    //Loading the data from xml file
    protected void LoadData()
    {
        DataSet ds = new DataSet();
        DataTable table = new DataTable();
        //reading xml file and loading listview.
        ds.ReadXml(xmlfile);
        lvEmployee.DataSource = ds;
        //binding dataset to listview.
        lvEmployee.DataBind();
    }

    // onclick of insert button in listview

    protected void lvEmployee_ItemInserting(object sender, ListViewInsertEventArgs e)
    {
        TextBox txtidTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtID");
        TextBox txtnameTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtName");
        // loading xml file
        XmlDocument xdoc = new XmlDocument();
        xdoc.Load(xmlfile);

        //Creating childnode to root node using Xmlelement
        XmlElement xelement = xdoc.CreateElement("Employee");
        //creating subnode to childnode using XmlElement
        XmlElement xID = xdoc.CreateElement("ID");
        xID.InnerText = txtidTextBox.Text;
        xelement.AppendChild(xID);

        //creating subnode to childnode using XmlElement
        XmlElement xName = xdoc.CreateElement("Name");
        xName.InnerText = txtnameTextBox.Text;
        xelement.AppendChild(xName);

        //Adding childnode to the root node.(in my case "NewElement is root node")
        xdoc.DocumentElement.AppendChild(xelement);
        xdoc.Save(xmlfile);
        LoadData();
    }

    // onclick of edit button in listview

    static Int16 i = 0;// based on the requirement we can change the declaration of variable i.

    protected void lvEmployee_ItemEditing(object sender, ListViewEditEventArgs e)
    {
        //getting the index value of particular row on click of edit button
        lvEmployee.EditIndex = e.NewEditIndex;
        i = Convert.ToInt16(lvEmployee.EditIndex);

        // to get the values from label which is inside listview, we need FindControl
        Label lblid = (Label)lvEmployee.EditItem.FindControl("lblID");
        Label lblname = (Label)lvEmployee.EditItem.FindControl("lblName");

        // to get the values from textbox which is inside listview, we need FindControl
        TextBox txtidTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtID");
        TextBox txtnameTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtName");
        txtidTextBox.Text = lblid.Text;
        txtidTextBox.Visible = false;
        txtnameTextBox.Text = lblname.Text;

    }

    protected void lvEmployee_ItemDeleting(object sender, ListViewDeleteEventArgs e)
    {
        // to get the values from label which is inside listview, we need FindControl
        Label lbl = (lvEmployee.Items[e.ItemIndex].FindControl("lblID")) as Label;
        Label lblName = (lvEmployee.Items[e.ItemIndex].FindControl("lblName")) as Label;
        //loading xml file using Xmldocument.
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(xmlfile);
        XmlNodeList newXMLNodes = xmlDoc.SelectNodes("/NewElement/Employee");

        // here i am searching based on id and name.So i am concatenating data into one string variable.
        string value = lbl.Text + lblName.Text;

        // code to remove child node from xml based on selection(matches all the data in xml file)
        //when a match is found removes that childnode from root node.
        foreach (XmlNode newXMLNode in newXMLNodes)
        {
            if (newXMLNode.InnerText == value)
            {
                newXMLNode.ParentNode.RemoveChild(newXMLNode);
            }
        }
        //saving back xml file and reloading listview.
        xmlDoc.Save(xmlfile);
        xmlDoc = null;
        LoadData();


    }

    protected void lvEmployee_ItemCanceling(object sender, ListViewCancelEventArgs e)
    {
        // to clear the textbox data.. (reset)
        TextBox txtidTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtID");
        TextBox txtnameTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtName");
        txtidTextBox.Text = string.Empty;
        txtnameTextBox.Text = string.Empty;
    }


    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            // to get the values from label which is inside listview, we need FindControl
            Label lblid = (Label)lvEmployee.EditItem.FindControl("lblID");
            Label lblname = (Label)lvEmployee.EditItem.FindControl("lblName");
            // to get the values from textbox which is inside listview, we need FindControl
            TextBox txtidTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtID");
            TextBox txtnameTextBox = (TextBox)lvEmployee.InsertItem.FindControl("txtName");
            //loading xml file
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(xmlfile);

            // Index value will be obtained at lvEmployee_ItemEditing ,that index value
            //is used here for update.
            XmlNode xmlnode = xmldoc.DocumentElement.ChildNodes.Item(i);
            xmlnode["ID"].InnerText = lblid.Text;
            xmlnode["Name"].InnerText = txtnameTextBox.Text;
            // save xml file and reload listview.
            xmldoc.Save(xmlfile);
            LoadData();
        }
        catch
        {
        }
    }

}

Paging button more functionality in List View .net c sharp

===================view================
<form id="form1" runat="server">
    <div class="StatusMessage">
        <asp:ListView ID="lvEmployee" runat="server" OnDataBound="lvEmployee_DataBound">
            <LayoutTemplate>
                <table id="itemPlaceholderContainer">
                    <tr runat="server" id="itemPlaceholder">
                    </tr>
                </table>
            </LayoutTemplate>
            <ItemTemplate>
                <tr>
                    <td>
                        Address:<asp:Label ID="AddressLabel" runat="server" Text='<%# Eval("Id") %>' />
                    </td>
                </tr>
            </ItemTemplate>
        </asp:ListView>
        <div id="divpaging" runat="server">
            <asp:DataPager ID="DataPager1" runat="server" PagedControlID="lvEmployee"
                OnPreRender="DataPager1_PreRender">
                <Fields>
                    <asp:TemplatePagerField OnPagerCommand="listPages_Click">
                        <PagerTemplate>
                            <asp:Button ID="listPages" runat="server" Text="more"></asp:Button>
                        </PagerTemplate>
                    </asp:TemplatePagerField>
                </Fields>
            </asp:DataPager>
        </div>
    </div>
    </form>
================================Code=========================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class listview_paging : System.Web.UI.Page
{

        int CurrentPage = 2;

        public int PageNumber
        {
            get
            {
                if (ViewState["PageNumber"] != null)
                    return Convert.ToInt32(ViewState["PageNumber"]);
                else
                    return 0;
            }
            set
            {
                ViewState["PageNumber"] = value;

            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                PageNumber = 1;
                DataPager1.PageSize = 2;
                ProductList db = new ProductList();
                lvEmployee.DataSource = db.GellAll();
                lvEmployee.DataBind();

            }

        }

        protected void lvEmployee_DataBound(object sender, EventArgs e)
        {

            int PageCount = (DataPager1.TotalRowCount / 2);

            if (PageCount * 2 != DataPager1.TotalRowCount)
            {

                PageCount = PageCount + 1;

            }

        }

        protected void DataPager1_PreRender(object sender, EventArgs e)
        {

            ProductList db = new ProductList();
            lvEmployee.DataSource = db.GellAll();
            lvEmployee.DataBind();

        }

        protected void listPages_Click(object sender, EventArgs e)
        {
            decimal PageCount = (decimal)((decimal)DataPager1.TotalRowCount / 2);

            if (PageNumber < PageCount)
            {
                PageNumber = PageNumber + 1;
                if (PageNumber >= PageCount)
                {
                    divpaging.Attributes["style"] = "display:none;";
                }
            }
            else
            {
                divpaging.Attributes["style"] = "display:none;";
            }

            int PageSize = 2 * PageNumber;//CurrentPage

            DataPager1.SetPageProperties(0, PageSize, true);
        }

    }

Sunday, 6 January 2019

All Table Count and calculate Space in SQL server

SELECT
    t.NAME AS TableName,
    s.Name AS SchemaName,
    p.rows AS RowCounts,
    SUM(a.total_pages) * 8 AS TotalSpaceKB,
    CAST(ROUND(((SUM(a.total_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS TotalSpaceMB,
    SUM(a.used_pages) * 8 AS UsedSpaceKB,
    CAST(ROUND(((SUM(a.used_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS UsedSpaceMB,
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB,
    CAST(ROUND(((SUM(a.total_pages) - SUM(a.used_pages)) * 8) / 1024.00, 2) AS NUMERIC(36, 2)) AS UnusedSpaceMB
FROM
    sys.tables t
INNER JOIN    
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
    sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN
    sys.schemas s ON t.schema_id = s.schema_id
WHERE
    t.NAME NOT LIKE 'dt%'
    AND t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255
GROUP BY
    t.Name, s.Name, p.Rows
ORDER BY
    t.Name

Wednesday, 19 December 2018

Multiple Models in Single View in MVC

Introduction
In MVC we cannot pass multiple models from a controller to the single view. This article provides a workaround for multiple models in a single view in MVC.

Problem Statement
Suppose I have two models, Teacher and Student, and I need to display a list of teachers and students within a single view. How can we do this?

The following are the model definitions for the Teacher and Student classes.
  1. public class Teacher  
  2. {  
  3.     public int TeacherId { get; set; }  
  4.     public string Code { get; set; }  
  5.     public string Name { get; set; }  
  6. }   
  7.   
  8. public class Student  
  9. {  
  10.     public int StudentId { get; set; }  
  11.     public string Code { get; set; }  
  12.     public string Name { get; set; }  
  13.     public string EnrollmentNo { get; set; }  
  14. }  
The following are the methods that help us to get all the teachers and students.
  1. private List<Teacher> GetTeachers()  
  2. {  
  3.     List<Teacher> teachers = new List<Teacher>();  
  4.     teachers.Add(new Teacher { TeacherId = 1, Code = "TT", Name = "Tejas Trivedi" });  
  5.     teachers.Add(new Teacher { TeacherId = 2, Code = "JT", Name = "Jignesh Trivedi" });  
  6.     teachers.Add(new Teacher { TeacherId = 3, Code = "RT", Name = "Rakesh Trivedi" });  
  7.     return teachers;  
  8. }   
  9.   
  10. public List<Student> GetStudents()  
  11. {  
  12.     List<Student> students = new List<Student>();  
  13.     students.Add(new Student { StudentId = 1, Code = "L0001", Name = "Amit Gupta", EnrollmentNo = "201404150001" });  
  14.     students.Add(new Student { StudentId = 2, Code = "L0002", Name = "Chetan Gujjar", EnrollmentNo = "201404150002" });  
  15.     students.Add(new Student { StudentId = 3, Code = "L0003", Name = "Bhavin Patel", EnrollmentNo = "201404150003" });  
  16.     return students;  
  17. }  
Required output
output

Solution
There are many ways to use multiple models with a single view. Here I will explain ways one by one.

1. Using Dynamic Model
ExpandoObject (the System.Dynamic namespace) is a class that was added to the .Net Framework 4.0 that allows us to dynamically add and remove properties onto an object at runtime. Using this ExpandoObject, we can create a new object and can add our list of teachers and students into it as a property. We can pass this dynamically created object to the view and render list of the teacher and student.

Controller Code
  1. public class HomeController : Controller  
  2. {  
  3.     public ActionResult Index()  
  4.     {  
  5.         ViewBag.Message = "Welcome to my demo!";  
  6.         dynamic mymodel = new ExpandoObject();  
  7.         mymodel.Teachers = GetTeachers();  
  8.         mymodel.Students = GetStudents();  
  9.         return View(mymodel);  
  10.     }  
  11. }  
We can define our model as dynamic (not a strongly typed model) using the @model dynamic keyword.

View Code
  1. @using MultipleModelInOneView;  
  2. @model dynamic  
  3. @{  
  4.     ViewBag.Title = "Home Page";  
  5. }  
  6. <h2>@ViewBag.Message</h2>  
  7.    
  8. <p><b>Teacher List</b></p>  
  9.    
  10. <table>  
  11.     <tr>  
  12.         <th>Id</th>  
  13.         <th>Code</th>  
  14.         <th>Name</th>  
  15.     </tr>  
  16.     @foreach (Teacher teacher in Model.Teachers)  
  17.     {  
  18.         <tr>  
  19.             <td>@teacher.TeacherId</td>  
  20.             <td>@teacher.Code</td>  
  21.             <td>@teacher.Name</td>  
  22.         </tr>  
  23.     }  
  24. </table>  
  25.    
  26. <p><b>Student List</b></p>  
  27.    
  28. <table>  
  29.     <tr>  
  30.         <th>Id</th>  
  31.         <th>Code</th>  
  32.         <th>Name</th>  
  33.         <th>Enrollment No</th>  
  34.     </tr>  
  35.     @foreach (Student student in Model.Students)  
  36.     {  
  37.         <tr>  
  38.             <td>@student.StudentId</td>  
  39.             <td>@student.Code</td>  
  40.             <td>@student.Name</td>  
  41.             <td>@student.EnrollmentNo</td>  
  42.         </tr>  
  43.     }  
  44. </table>  
2. Using View Model
ViewModel is nothing but a single class that may have multiple models. It contains multiple models as a property. It should not contain any method.

In the above example, we have the required View model with two properties. This ViewModel is passed to the view as a model. To get intellisense in the view, we need to define a strongly typed view.
  1. public class ViewModel  
  2. {  
  3.     public IEnumerable<Teacher> Teachers { get; set; }  
  4.     public IEnumerable<Student> Students { get; set; }  
  5. }  
Controller code
  1. public ActionResult IndexViewModel()  
  2. {  
  3.     ViewBag.Message = "Welcome to my demo!";  
  4.     ViewModel mymodel = new ViewModel();  
  5.     mymodel.Teachers = GetTeachers();  
  6.     mymodel.Students = GetStudents();  
  7.     return View(mymodel);  
  8. }  
View code
  1. @using MultipleModelInOneView;  
  2. @model ViewModel   
  3. @{  
  4.     ViewBag.Title = "Home Page";  
  5. }  
  6. <h2>@ViewBag.Message</h2>  
  7.    
  8. <p><b>Teacher List</b></p>  
  9.    
  10. <table>  
  11.     <tr>  
  12.         <th>Id</th>  
  13.         <th>Code</th>  
  14.         <th>Name</th>  
  15.     </tr>  
  16.     @foreach (Teacher teacher in Model.Teachers)  
  17.     {  
  18.         <tr>  
  19.             <td>@teacher.TeacherId</td>  
  20.             <td>@teacher.Code</td>  
  21.             <td>@teacher.Name</td>  
  22.         </tr>  
  23.     }  
  24. </table>  
  25.    
  26. <p><b>Student List</b></p>  
  27.    
  28. <table>  
  29.     <tr>  
  30.         <th>Id</th>  
  31.         <th>Code</th>  
  32.         <th>Name</th>  
  33.         <th>Enrollment No</th>  
  34.     </tr>  
  35.     @foreach (Student student in Model.Students)  
  36.     {  
  37.         <tr>  
  38.             <td>@student.StudentId</td>  
  39.             <td>@student.Code</td>  
  40.             <td>@student.Name</td>  
  41.             <td>@student.EnrollmentNo</td>  
  42.         </tr>  
  43.     }  
  44. </table>  
3. Using ViewData 
ViewData is used to transfer data from the controller to the view. ViewData is a dictionary object that may be accessible using a string as the key. Using ViewData, we can pass any object from the controller to the view. The Type Conversion code is required when enumerating in the view. 
For the preceding example, we need to create ViewData to pass a list of teachers and students from the controller to the view.

Controller Code
  1. public ActionResult IndexViewData()  
  2. {  
  3.     ViewBag.Message = "Welcome to my demo!";  
  4.     ViewData["Teachers"] = GetTeachers();  
  5.     ViewData["Students"] = GetStudents();  
  6.     return View();  
  7. }  
View Code
  1. @using MultipleModelInOneView;  
  2. @{  
  3.     ViewBag.Title = "Home Page";  
  4. }  
  5. <h2>@ViewBag.Message</h2>  
  6.  <p><b>Teacher List</b></p>   
  7. @{  
  8.   
  9.    IEnumerable<Teacher> teachers = ViewData["Teachers"] as IEnumerable<Teacher>;  
  10.    IEnumerable<Student> students = ViewData["Students"] as IEnumerable<Student>;  
  11. }  
  12. <table>  
  13.     <tr>  
  14.         <th>Id</th>  
  15.         <th>Code</th>  
  16.         <th>Name</th>  
  17.     </tr>  
  18.     @foreach (Teacher teacher in teachers)  
  19.     {  
  20.         <tr>  
  21.             <td>@teacher.TeacherId</td>  
  22.             <td>@teacher.Code</td>  
  23.             <td>@teacher.Name</td>  
  24.         </tr>  
  25.     }  
  26. </table>  
  27.  <p><b>Student List</b></p>  
  28. <table>  
  29.     <tr>  
  30.         <th>Id</th>  
  31.         <th>Code</th>  
  32.         <th>Name</th>  
  33.         <th>Enrollment No</th>  
  34.     </tr>  
  35.     @foreach (Student student in students)  
  36.     {  
  37.         <tr>  
  38.             <td>@student.StudentId</td>  
  39.             <td>@student.Code</td>  
  40.             <td>@student.Name</td>  
  41.             <td>@student.EnrollmentNo</td>  
  42.         </tr>  
  43.     }  
  44. </table>  
4. Using ViewBag
ViewBag is similar to ViewData and is also used to transfer data from the controller to the view. ViewBag is a dynamic property. ViewBag is just a wrapper around the ViewData.

Controller Code
  1. public ActionResult IndexViewBag()  
  2. {  
  3.     ViewBag.Message = "Welcome to my demo!";  
  4.     ViewBag.Teachers = GetTeachers();  
  5.     ViewBag.Students = GetStudents();  
  6.     return View();  
  7. }  
View Code
  1. @using MultipleModelInOneView;  
  2. @{  
  3.     ViewBag.Title = "Home Page";  
  4. }  
  5. <h2>@ViewBag.Message</h2>  
  6.    
  7. <p><b>Teacher List</b></p>  
  8.    
  9. <table>  
  10.     <tr>  
  11.         <th>Id</th>  
  12.         <th>Code</th>  
  13.         <th>Name</th>  
  14.     </tr>  
  15.     @foreach (Teacher teacher in ViewBag.Teachers)  
  16.     {  
  17.         <tr>  
  18.             <td>@teacher.TeacherId</td>  
  19.             <td>@teacher.Code</td>  
  20.             <td>@teacher.Name</td>  
  21.         </tr>  
  22.     }  
  23. </table>  
  24.    
  25. <p><b>Student List</b></p>  
  26.    
  27. <table>  
  28.     <tr>  
  29.         <th>Id</th>  
  30.         <th>Code</th>  
  31.         <th>Name</th>  
  32.         <th>Enrollment No</th>  
  33.     </tr>  
  34.     @foreach (Student student in ViewBag.Students)  
  35.     {  
  36.         <tr>  
  37.             <td>@student.StudentId</td>  
  38.             <td>@student.Code</td>  
  39.             <td>@student.Name</td>  
  40.             <td>@student.EnrollmentNo</td>  
  41.         </tr>  
  42.     }  
  43. </table>  
5. Using Tuple
A Tuple object is an immutable, fixed-size and ordered sequence object. It is a data structure that has a specific number and sequence of elements. The .NET framework supports tuples up to seven elements.

Using this tuple object we can pass multiple models from the controller to the view.

Controller Code
  1. public ActionResult IndexTuple()  
  2. {  
  3.     ViewBag.Message = "Welcome to my demo!";  
  4.     var tupleModel = new Tuple<List<Teacher>, List<Student>>(GetTeachers(), GetStudents());  
  5.     return View(tupleModel);  
  6. }  
View Code
  1. @using MultipleModelInOneView;  
  2. @model Tuple <List<Teacher>, List <Student>>  
  3. @{  
  4.     ViewBag.Title = "Home Page";  
  5. }  
  6. <h2>@ViewBag.Message</h2>   
  7. <p><b>Teacher List</b></p>  
  8. <table>  
  9.     <tr>  
  10.         <th>Id</th>  
  11.         <th>Code</th>  
  12.         <th>Name</th>  
  13.     </tr>  
  14.     @foreach (Teacher teacher in Model.Item1)  
  15.     {  
  16.         <tr>  
  17.             <td>@teacher.TeacherId</td>  
  18.             <td>@teacher.Code</td>  
  19.             <td>@teacher.Name</td>  
  20.         </tr>  
  21.     }  
  22. </table>  
  23. <p><b>Student List</b></p>  
  24. <table>  
  25.     <tr>  
  26.         <th>Id</th>  
  27.         <th>Code</th>  
  28.         <th>Name</th>  
  29.         <th>Enrollment No</th>  
  30.     </tr>  
  31.     @foreach (Student student in Model.Item2)  
  32.     {  
  33.         <tr>  
  34.             <td>@student.StudentId</td>  
  35.             <td>@student.Code</td>  
  36.             <td>@student.Name</td>  
  37.             <td>@student.EnrollmentNo</td>  
  38.         </tr>  
  39.     }  
  40. </table>  
6. Using Render Action Method
A Partial View defines or renders a partial view within a view. We can render some part of a view by calling a controller action method using the Html.RenderAction method. The RenderAction method is very useful when we want to display data in the partial view. The disadvantages of this method is that there are only multiple calls of the controller.

In the following example, I have created a view (named partialView.cshtml) and within this view I called the html.RenderAction method to render the teacher and student list.

Controller Code
  1. public ActionResult PartialView()  
  2. {  
  3.     ViewBag.Message = "Welcome to my demo!";  
  4.     return View();  
  5. }  
  6.    
  7. /// <summary>  
  8. /// Render Teacher List  
  9. /// </summary>  
  10. /// <returns></returns>  
  11. public PartialViewResult RenderTeacher()  
  12. {  
  13.     return PartialView(GetTeachers());  
  14. }  
  15.    
  16. /// <summary>  
  17. /// Render Student List  
  18. /// </summary>  
  19. /// <returns></returns>  
  20. public PartialViewResult RenderStudent()  
  21. {  
  22.     return PartialView(GetStudents());  
  23. }  
View Code
  1. @{  
  2.    ViewBag.Title = "PartialView";  
  3. <h2>@ViewBag.Message</h2>  
  4. <div>  
  5.     @{  
  6.         Html.RenderAction("RenderTeacher");  
  7.         Html.RenderAction("RenderStudent");  
  8.     }  
  9. </div>  
RenderTeacher.cshtml
  1. @using MultipleModelInOneView;  
  2. @model IEnumerable<MultipleModelInOneView.Teacher>  
  3.  <p><b>Teacher List</b></p>  
  4. <table>  
  5.     <tr>  
  6.         <th>Id</th>  
  7.         <th>Code</th>  
  8.         <th>Name</th>  
  9.     </tr>  
  10.     @foreach (Teacher teacher in Model)  
  11.     {  
  12.         <tr>  
  13.             <td>@teacher.TeacherId</td>  
  14.             <td>@teacher.Code</td>  
  15.             <td>@teacher.Name</td>  
  16.         </tr>  
  17.     }  
  18. </table>  
RenderStudent.cshtml
  1. @using MultipleModelInOneView;  
  2. @model IEnumerable<MultipleModelInOneView.Student>   
  3.   
  4. <p><b>Student List</b></p>  
  5. <table>  
  6.     <tr>  
  7.         <th>Id</th>  
  8.         <th>Code</th>  
  9.         <th>Name</th>  
  10.         <th>Enrollment No</th>  
  11.     </tr>  
  12.     @foreach (Student student in Model)  
  13.     {  
  14.         <tr>  
  15.             <td>@student.StudentId</td>  
  16.             <td>@student.Code</td>  
  17.             <td>@student.Name</td>  
  18.             <td>@student.EnrollmentNo</td>  
  19.         </tr>  
  20.     }  
  21. </table>  

Conclusion 
This article helps us to learn how to pass multiple models from the controller to the view. I hope this will be helpful for beginners.