Saturday, 10 February 2018

Fill Drop down list using razor

Store Procedure


USE [Girfa_ProductDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[fetchProduct]
AS
BEGIN
     select  id,productname from dbo.product order by productname
END


CHTML

@model IEnumerable<Britanic_MIS.Models.ProductModel>

Product : 
<select class="form-control
">
<option value="">Select Product</option>   
@foreach (var item in Model)
{
<option value="@item.ID">@item.productname</option>
}
</select>

Model

public class ProductModel
{
        public string ID { set; get; }
        public string productname { set; get; }
}

Controller

public ActionResult StockDetail()
{
List<ProductModel> list = new List<ProductModel>();
ICustomerRepository ob = new CustomerRepository();
list = ob.ProductList();
return View(list);
}

Repository

public List<ProductModel> ProductList()
{
    List<ProductModel> Record = new List<ProductModel>();
    try
    {
        using (SqlConnection dbcon = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ToString()))
        {

            using (SqlCommand cmd = new SqlCommand("[dbo].[Fetchproduct]", dbcon))
            {
                cmd.CommandType = CommandType.StoredProcedure;

                if (dbcon.State == ConnectionState.Closed)
                    dbcon.Open();
                using (SqlDataReader dr = cmd.ExecuteReader())
                {

                    if (dr.HasRows)
                    {
                        //Record.Add(new SelectListItem { Text = "Select SE" });
                        while (dr.Read())
                        {

                            ProductModel data = new ProductModel();
                            data.ID = dr.IsDBNull(0) ? "0" : Convert.ToString(dr[0]);
                            data.productname = dr.IsDBNull(1) ? "0" : Convert.ToString(dr[1]);
                        }
                    }
                }

            }
        }
    }
    catch (Exception ex)
    {

    }
    return Record;
}