Monday, March 4, 2019

Binding Model to View and Display data

In the previous post we saw on how to create a Model class, in this post we will use the model class in the controller to populate the model properties and pass on a list of Model objects to the view layer to display the data in the view.

In the controller we will instantiate the model class set values to its properties and bind it with the view to display the data. Next let us edit the Home controller and initialize the model object as follows.

    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            var productModel = GetProducts();
            return View(productModel);
        }

        private List<Product> GetProducts()
        {
            List<Product> lstProducts = new List<Product>();
            lstProducts.Add(new Product(1, "LL Crankarm", "CA-5965", 10.00));
            lstProducts.Add(new Product(1, "ML Crankarm", "CA-6738", 15.00));
            lstProducts.Add(new Product(1, "HL Crankarm", "CA-7457", 25.00));
            lstProducts.Add(new Product(1, "Chainring Bolts", "CB-2903", 40.00));
            lstProducts.Add(new Product(1, "Chainring Nut", "CN-6137", 50.00));

            return lstProducts;
        }
    }

In this sample we will not get the data from database, instead we create a static set of products in the GetProducts() method and pass on the list of Model objects to the view.  In the view we bind the Model class and display the data sent from the controller in a table format. The view code looks as follows.

@model IEnumerable<HelloMVC.Models.Product>

<div class="text-center">
    <table class="table">
        <thead>
            <tr>
                <th>ProductID</th>
                <th>Name</th>
                <th>ProductNumber</th>
                <th>Cost</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.ProductID)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Name)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.ProductNumber)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Cost)
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>

Build and run the project, the output will be as follows.




Search Flipkart Products:
Flipkart.com

No comments: