Monday 15 May 2017

Pass (Send) DataSet (DataTable) from Controller to View in ASP.Net MVC

Pass (Send) DataSet (DataTable) from Controller to View in ASP.Net MVC

Description:
In this example we explain that how to pass DataTable from Controller to View in MVC in asp.net MVC,or how to pass or send DataTable from controller to View in MVC. Suppose you have List of the Employee List and you want to display it in gridview so this type of scenario that example is used to pass or send Employee DataTable or DataSet from controller to View in MVC.

Here we demonstrate that how to pass or send DataSet or DataTable from controller to View in Asp.Net MVC Razor.
Controller:

using System.Data;
using System.Configuration;
using System.Data.SqlClient;

public class EmployeeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        DataSet ds = new DataSet();
        string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            string query = "SELECT * FROM Employees";
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.Connection = con;
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    sda.Fill(ds);
                }
            }
        }

        return View(ds);
    }
}

View: 

@using System.Data
@model DataSet
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <table cellpadding="0" cellspacing="0">
        <tr>
            <th>EmployeeId</th>
            <th>Employee Name</th>
            <th>Designatation</th>
        </tr>
        @foreach (DataRow row in Model.Tables[0].Rows)
        {
            <tr>
                <td>@row["EmployeeId"]</td>
                <td>@row["Name"]</td>
                <td>@row["Designatation"]</td>
            </tr>
        }
    </table>
</body>
</html>



This entry was posted in :

0 comments:

Post a Comment