Search code examples
c#asp.net-mvcasp.net-mvc-4dropdownlistfor

How to access a dropdown list control id in action of controller


I want to implement a function which is already written in asp.net application of my colleague.I want to implement the same logic in asp.net mvc but i don't know how to get the id of a dropdownlist control in action of a controller What he has done is he is population a dropdwonlist by calling a function shown below

Global.BindRigionByApplicationAccess(drpRegion,
                                     ConfigurationManager.AppSettings["ApplicationId"],
                                     ref ErrorMessage);

here 'drpRegion' is id of dropdownlist , in asp.net just a simple call will of that function will load data.

I did following code in asp.net mvc

in view

@Html.DropDownList("REGION_CODE", (SelectList)ViewBag.gpregions)

Solution

  • You can't pass the dropdown control to LoadDropDown method since controllers don't know anything about the html controls. What you need to do is the following:

    1. Get the data from database.
    2. Generate an instance of List<SelectListItem> based on the data.
    3. Pass the instance of List<SelectListItem> to the view
    4. Use the instance of List<SelectListItem> as the second parameter of @Html.DropDownList helper method in the view.

    Let's start with DataAccessLib class. I would create the following method that returns a Dictionary<string, string>

    public Dictionary<string, string> GetDropdownItems(string sQuery, string sDTextField, string sDValueField)
    {
        Dictionary<string, string> dict = new Dictionary<string, string>();
    
        using (OracleConnection odConn = new OracleConnection(sConnStr))
        {
            odConn.Open();
            OracleCommand odCmd = odConn.CreateCommand();
            odCmd.CommandText = sQuery;
            using (var dr = odCmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    dict[dr[sDValueField].ToString()] = dr[sDTextField].ToString();
                }
            }
        }
        return dict;
    }
    

    then create the below method in Global class. Basically it sets the query, calls the above method, and generates an instance of List<SelectListItem>

    public static List<SelectListItem> GetRegionDropdownItems(string ApplicationId, ref string ErrorMessage)
    {
        string query = @"SELECT distinct GP_REGION.REGION_MAIN Region_Code,
        R1.REGION_NAME FROM GP_REGION INNER JOIN GP_REGION R1 
        ON GP_REGION.REGION_MAIN = R1.REGION_CODE WHERE GP_REGION.REGION_HAS_DATA='Y'
        AND GP_REGION.REGION_MAIN IN (SELECT DISTINCT AR.BRANCH_CODE FROM PORTAL.UA_APPLN_ROLE AR 
        INNER JOIN PORTAL.UA_GROUP G ON AR.GROUP_CODE = G.GROUP_CODE
        WHERE G.USER_ID = '" + Global.UserId() + "' AND AR.APPLICATION_ID = '" + ApplicationId + "') ORDER BY GP_REGION.REGION_MAIN";
    
        // get the regions from database
        DataAccessLib dal = new DataAccessLib(Global.ConnectionString());
        Dictionary<string, string> regions = dal.GetDropdownItems(query, "REGION_NAME", "Region_Code");
    
        // generate the dropdown items
        List<SelectListItem> ddlItems = new List<SelectListItem>();
        foreach (var key in regions.Keys)
        {
            ddlItems.Add(new SelectListItem() { Selected = false, Text = regions[key], Value = key });
        }
    
        return ddlItems;
    }
    

    then call Global.GetRegionDropdownItems and set the results to ViewBag.Regions in your controller

    public ActionResult _GetRegions()
    {
        List<SelectListItem> ddlItems = Global.GetRegionDropdownItems(
                                            ConfigurationManager.AppSettings["ApplicationId"],
                                            ref ErrorMessage);
        ViewBag.Regions = ddlItems;
    
        return PartialView();
    }
    

    and finally use the @Html.DropDownList helper method in your view as below

    @Html.DropDownList("REGION_CODE", (List<SelectListItem>)ViewBag.Regions)