How to bind and get list of data from view to controller Action Method with Model using MVC

Going to develop MVC application to bind data and get list of data from view to controller using dotnet core MVC c#.

For development this I have used :-
Visual studion 2019
Sql server
Entity Framework core

Process to Develop Application
Open visual studio 2019 
Click on Create New Project then window will open

Select Asp.net Core Web Application and click on Next Button then window will be open
Here specify 
Name        -> Name of Project you want
Location    -> Select/Specify Location where you want to create Project.
Solution Name    ->Solution Name will be same as Project Name
Click on Create Button then window will open as- 

Here Select Web Application (Model-View-Controller) and uncheck Configure for Https
And Click on Create Button your project will be created.


Process to Connect with Sql Server database
Add below Packages using Nuget package manager

Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Tools

Go to solution explorer -> Right Click on Project -> Click on Manage NuGet Packages

Window will open then click on Browse tab and in search tab type above package and click on install then popup window will open then click on Accept button then your packages will be install on your project as

Create Table in Sql server Database 


CREATE TABLE [dbo].[CRUDEmployee](
    [EmployeeID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NULL,
    [Position] [varchar](50) NULL,
    [Office] [varchar](50) NULL,
    [Salary] [int] NULL,
    [ImagePath] [varchar](500) NULL,
PRIMARY KEY CLUSTERED 
(
    [EmployeeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

Connect with Database First Approach
Go to Tools -> Nuget Package Manager -> Package manager Console
Then window will open below
Type below Command to Create ContextClass of all tables in database
Scaffold-DbContext "Server=DESKTOP-I6QIQ9N;Database=MVC_Test_DB;Trusted_Connection=True;User Id=sa;Password=Shashi;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context "MVCTestDBContext"

Type below Command to Create Context Class to Add Specific Table
Scaffold-DbContext "server=DESKTOP-I6QIQ9N;user=sa;password=Shashi;database=EINVOICE" Microsoft.EntityFrameworkCore.SqlServer -OutputDir DBModel -Context "MVCTestDBContext" -Tables CRUDEmployee

After adding Context Class Folder will be create in Solution Explorer
Also Context class as well as database table class will be created on Folder.
In Context Class Connection automatically Created you can check –
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer("server=DESKTOP-I6QIQ9N;user id=sa;password=Shashi;database=EINVOICE;");
            }
        }
Below is screen shoot.

Create Model Class in Model Folder As –

public CRUDEmployeeModel GetEmployee_Details()
        {
            CRUDEmployeeModel cmodel = new CRUDEmployeeModel();
            List<EmployeeListModel> listm = new List<EmployeeListModel>();           
            var validCustomers = from c in db.Crudemployee select c;            
            foreach (var cust in validCustomers)
            {
                var em =new EmployeeListModel();
                em.EmployeeId = cust.EmployeeId;
                em.Name = cust.Name;
                em.Position = cust.Position;
                em.Office = cust.Office;
                em.Salary = cust.Salary;
                listm.Add(em);
            }

            cmodel.Header1 = "shashi";
            cmodel.Header2 = "Bhushan";
            cmodel.lstempdata = listm;
            return cmodel;
        }
public class EmployeeListModel
    {
        MVCTestDBContext db = new MVCTestDBContext();
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string Position { get; set; }
        public string Office { get; set; }
        public int? Salary { get; set; }
}

Add Empty Controller with Name CRUDEmployee  and write code as bellow-

public IActionResult Index()
        {            
            CRUDEmployeeModel m1 = new CRUDEmployeeModel();
            m1= m1.GetEmployee_Details();
            return View(m1);
        }

        [HttpPost]
        public IActionResult Index(CRUDEmployeeModel obj)
        {
            return View();
        }

Note:- Here Index Post method place breake point and you can check you view data.

Create Index View As-

@model CRUDEmployeeModel
@{
    ViewData["Title"] = "IndexwithheaderVal";
}

    <div class="content-wrapper">
        @*@using (Html.BeginForm("PayAmount", "Home", null, FormMethod.Post))*@

        @using (Html.BeginForm("IndexwithheaderVal", "CRUDEmployee", null, FormMethod.Post))
        {
            <section class="content">
                <div class="row">
                    <div class="col-xs-12">
                        <div class="box">

                            <div class="box-header with-border">
                                <h3 class="box-title">                                   
                                    @Html.HiddenFor(m => m.Header1)
                                    @Html.HiddenFor(m => m.Header2)                                  
                                </h3>
                                <div class="box-tools pull-right">
                                    <button type="submit" id="btnPay" class="btn btn-info pull-right">Submit</button>
                                </div>
                            </div>

                            <!-- /.box-header -->
                            <div class="box-body" style="overflow:auto;">
                                <table id="example1" class="table table-bordered table-striped">
                                    <thead>
                                        <tr style="color:red">
                                            <th>
                                                @Html.Label("EmployeeId", ViewBag.CurrentFilter as string)
                                            </th>
                                            <th>
                                                @Html.Label("Name", ViewBag.CurrentFilter as string)
                                            </th>
                                            <th>
                                                @Html.Label("Position", ViewBag.CurrentFilter as string)
                                            </th>
                                            <th>
                                                @Html.Label("Office", ViewBag.CurrentFilter as string)
                                            </th>
                                            <th>
                                                @Html.Label("Salary", ViewBag.CurrentFilter as string)
                                            </th>
                                        </tr>
                                    </thead>
                                   
                                    <tbody>

                                        @if (Model != null)
                                        {
                                            for (var i = 0; i < Model.lstempdata.Count; i++)
                                            {
                                                <tr>
                                                    <td style="color:red">
                                                        @Html.DisplayFor(modelItem => Model.lstempdata[i].EmployeeId)
                                                        @Html.HiddenFor(modelItem => Model.lstempdata[i].EmployeeId)
                                                    </td>
                                                    <td>
                                                        @Html.DisplayFor(modelItem => Model.lstempdata[i].Name)
                                                        @Html.HiddenFor(modelItem => Model.lstempdata[i].Name)
                                                    </td>
                                                    <td>
                                                        @Html.DisplayFor(modelItem => Model.lstempdata[i].Position)
                                                        @Html.HiddenFor(modelItem => Model.lstempdata[i].Position)
                                                    </td>
                                                    <td>
                                                        @Html.DisplayFor(modelItem => Model.lstempdata[i].Office)
                                                        @Html.HiddenFor(modelItem => Model.lstempdata[i].Office)
                                                    </td>
                                                    <td>
                                                        @Html.DisplayFor(modelItem => Model.lstempdata[i].Salary)
                                                        @Html.HiddenFor(modelItem => Model.lstempdata[i].Salary)
                                                    </td>
                                                </tr>
                                            }
                                        }
                                    </tbody>
                                </table>
                            </div>
                            <!-- /.box-body -->
                        </div>
                        <!-- /.box -->
                    </div>
                    <!-- /.col -->
                </div>
                <!-- /.row -->
            </section>
        }      
    </div>

Note:- Must set value in hidden field and also use for loop other wise you will not get list of data in action method.
 

Leave a Comment