Strongly Typed Model In Asp.Net MVC

In this article, you will understand What is Strongly Typed Model In Asp.Net MVC ?. How to Create Strongly Typed Model ? How Get data from DataBase for that model in Asp.Net MVC by Sagar Jaybhay.

Srtongly Typed Model

The flow of MVC is when you hit URL it first go to the Controllers‘ action method, the controller will search for if particular request required data or not if yes then it gets from Model and then this model is the pass to View.

Model View Controller in MVC
Model View Controller in MVC

For this, we create one table in SQL server,

Create table Employee
(
EmpID int,
EmpName nvarchar(20),
EmpSalary float,
EmpGender nvarchar(6),
EmpCity nvarchar(20),
EmpEmail nvarchar(20)
)

Our Model is

public class Employee
    {

        public int EmpID { get; set; }
        public string EmpName { get; set; }
        public double EmpSalary { get; set; }
        public string EmpGender { get; set; }
        public string EmpCity { get; set; }
        public string EmpEmail { get; set; }
    }

Below we create a strongly typed view and Employee class is our Model which we created in the Model folder in our MVC application.

How to add Strongly Typed Moedl
How to add Strongly Typed Moedl

To Make our view strongly typed use below the line of code

@model WebApplication1.Models.Employee

And generally, we write this is the first line in view.

Strongly Typed Model Data Binding To View
Strongly Typed Model Data Binding To View

To display the information we use strongly type HtmlHelpers and below is the syntax for that and in our application we use @model and by using the model we access the properties of Employee object.

<dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.EmpID)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.EmpID)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.EmpName)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.EmpName)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.EmpSalary)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.EmpSalary)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.EmpGender)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.EmpGender)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.EmpCity)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.EmpCity)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.EmpEmail)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.EmpEmail)
        </dd>

    </dl>
</div>

DataAccess In MVC

To access data from the database we create one table in a database and added records in that. Now to access data we create one project DAL in our MVC application and refer it in the MVC application. DAL project contains a DataAccess class in which our GetTable logic is present.

After this, we create one folder in our MVC application as BusineessLogic and added one class Business in that class we created the write GetEmployeeById method which returns a single Employee as a result. Now our Project has front-end, BusinnessLogic, and DataAccessLayer. We can also move our BusineessLogic to separate project but right now there is no need.

Below is our DataAccess Class when we need database related methods like ExecuteDML, GetDataSet like that.

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Configuration;

namespace DAL
{
    public class DataAccess
    {
       
        private string _ConnectionString { get ;set; }


        public DataAccess()
        {
            this._ConnectionString= ConfigurationManager.ConnectionStrings["SQLServerConnection"].ConnectionString;
        }

        public DataTable GetTable(string Query)
        {
            DataTable dataTable = new DataTable();
            try
            {
                using(var con=new SqlConnection(this._ConnectionString))
                {
                    con.Open();
                    var cmd = new SqlCommand(Query, con);
                    var adp = new SqlDataAdapter(cmd);
                    adp.Fill(dataTable);
                    cmd.Dispose();
                    adp.Dispose();
                    return dataTable;
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
            return null;
        }
    }
}

After this below is Our Business Class in which our main logic resides. As per our need, we can add Methods here also.

using DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebApplication1.Models;

namespace WebApplication1.BusinessLogic
{
    public class Business
    {
        private DataAccess dataAccess = null;
        public Business()
        {
            this.dataAccess = new DataAccess();

        }

        public Employee GetEmployee(string EmpId)
        {
            Employee employee;
            string Query = "select * from Employee where EmpID="+EmpId;
            var data = this.dataAccess.GetTable(Query);
            if(data!=null&&data.Rows.Count>0)
            {
                employee = new Employee()
                {
                    EmpID = Convert.ToInt32(data.Rows[0]["EmpID"]),
                    EmpCity = data.Rows[0]["EmpCity"].ToString(),
                    EmpEmail = data.Rows[0]["EmpEmail"].ToString(),
                    EmpGender = data.Rows[0]["EmpGender"].ToString(),
                    EmpName = data.Rows[0]["EmpName"].ToString(),
                    EmpSalary = Convert.ToDouble(data.Rows[0]["EmpSalary"].ToString())
                };

                return employee;
            }
            return null;

        }

    }
}

Now we modify our Employee controller Index method and pass their one parameter which is EmployeeId so when we pass that parameter from URL we get this.

public ActionResult Index(string EmpID)
        {
            Employee employee = new BusinessLogic.Business().GetEmployee(EmpID);

            return View(employee);
        }
    }

Strongly Typed Model Output
Strongly Typed Model Output

GitHub Project : https://github.com/Sagar-Jaybhay/MVC5

Sagar Jaybhay, from Maharashtra, India, is currently a Senior Software Developer at Software Company. He has continuously grown in the roles that he has held in the more than seven years he has been with this company. Sagar Jaybhay is an excellent team member and prides himself on his work contributions to his team and company as a whole.

Sagar Jaybhay

Sagar Jaybhay, from Maharashtra, India, is currently a Senior Software Developer at Software Company. He has continuously grown in the roles that he has held in the more than seven years he has been with this company. Sagar Jaybhay is an excellent team member and prides himself on his work contributions to his team and company as a whole.

You may also like...