How to load @Html.DropDownListFor using ASP.NET MVC ViewBag

Namespaces
You will need to import the following namespaces.
using System.Configuration;
using System.Data.SqlClient;
using System.Collections.Generic;




Controller
The Controller has one Action methods.

public ActionResult Index()
    {
        ViewBag.Plan = FinMosLOV(1, "Plan");
        return View();   
    }


 public List<SelectListItem> FinMosLOV(int parm1, string parm2)
        {
            List<SelectListItem> lst = new List<SelectListItem>();
            using (SqlConnection con = new SqlConnection(cs))
            {
                con.Open();
                SqlCommand com = new SqlCommand("SP_Name", con);
                com.CommandType = CommandType.StoredProcedure;
                      
                com.Parameters.AddWithValue("@FieldNum", parm1);

                SqlDataReader rdr = com.ExecuteReader();
                while (rdr.Read())
                {
                    lst.Add(new SelectListItem
                    {
                       
                        Text = (rdr[parm2].ToString()),

                        Value = (rdr[parm2].ToString())
                    });
                }
                return lst;
            }
        }


View
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
<div class="form-group">

            @Html.LabelFor(model => model.CurrentPlan, htmlAttributes: new { @class = "control-label col-md-2" })

            <div class="col-md-10">



                @Html.DropDownListFor(

               model => model.CurrentPlan,



               (IEnumerable<SelectListItem>)ViewBag.Plan

                , "Please select"



     , new { htmlAttributes = new { @class = "form-control" } }

               )



           



                @Html.ValidationMessageFor(model => model.CurrentPlan, "", new { @class = "text-danger" })

            </div>

        </div>





0 Comments