using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.Configuration;
using System.Data.SqlClient;
using System.Collections.Generic;
using Call_Controller_DropDownList_Change_MVC.Models;

namespace Call_Controller_DropDownList_Change_MVC.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            List<FruitModel> fruits = PopulateFruits();
            return View(fruits);
        }

        [HttpPost]
        public ActionResult Submit(FormCollection formcollection)
        {
            TempData["Message"] = "Fruit Name: " + formcollection["FruitName"];
            TempData["Message"] += "\\nFruit Id: " + formcollection["FruitId"]; ;
            return RedirectToAction("Index");
        }

        private static List<FruitModel> PopulateFruits()
        {
            List<FruitModel> fruits = new List<FruitModel>();
            string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                string query = "SELECT FruitName, FruitId FROM Fruits";
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            fruits.Add(new FruitModel
                            {
                                FruitName = sdr["FruitName"].ToString(),
                                FruitId = Convert.ToInt32(sdr["FruitId"])
                            });
                        }
                    }
                    con.Close();
                }
            }

            return fruits;
        }
    }
}