How to fill dropdownlist in MVC-4 using dapper

asp.net-mvc asp.net-mvc-4 dapper

Question

I filled Drop Down List in MVC which is working fine but now I want to do it using Dapper but got stuck.

DropDownList in MVC without Dapper

Controller

  [HttpPost]
    public ActionResult Create(User ur)
    {
        string str = @"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
        SqlConnection con = new SqlConnection(str);
        string query = "Insert into tblTest (Name,Email,MobileNo) values('" + ur.Name + "','" + ur.Email + "','" + ur.MobileNo + "')";
        con.Open();
        SqlCommand cmd = new SqlCommand(query, con);
        cmd.ExecuteNonQuery();
        con.Close();
        TempData["msg"] = "<script>alert('Inserted Successfully');</script>";
        ModelState.Clear();
        FillCountry();

    }
    public void FillCountry()
    {
        string str = @"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
        SqlConnection con = new SqlConnection(str);
        string query = "select * from tbl_country ";
        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        List<SelectListItem> li = new List<SelectListItem>();
        li.Add(new SelectListItem { Text = "Select", Value = "0" });
        while (rdr.Read())
        {
            li.Add(new SelectListItem { Text = rdr[1].ToString(), Value = rdr[0].ToString() });
        }

        ViewData["country"] = li;

    }

View

@{ Html.BeginForm("Create", "User", FormMethod.Post, new { enctype = "multipart/form-data" }); }
@Html.DropDownList("country", ViewData["country"] as List<SelectListItem>, new {onchange = "this.form.submit();" })
@{ Html.EndForm(); }

This is what I am trying to do now

DropDownList in MVC with Dapper

Model

public class Region
{
    private int _CountryId;
    private string _CountryName;

    public int CountryId
    {
        get { return _CountryId; }
        set { _CountryId = value; }
    }


    public string CountryName
    {
        get { return _CountryName; }
        set { _CountryName = value; }
    }

Controller

[HttpPost]
    public ActionResult AddMobiles(TBMobileDetails MD, HttpPostedFileBase file)
    {
        FileUpload(file);
        MobileMain MM = new MobileMain();
        MM.AddMobiles(MD);
        FillCountry();         
        return RedirectToAction("AllMobileList");
    }

Stuck in this part how to fill it using dapper? How to populate my list?

    public void FillCountry()
    {
        List<Region> li = new List<Region>();
        var para = new DynamicParameters();
        para.Add("@Type", 1);
        var result = con.Query<Region>("Sp_MVCDapperDDl", para, commandType: CommandType.StoredProcedure);
    }

View

  @{ Html.BeginForm("AddMobiles", "AddMobile", FormMethod.Post, new { enctype = "multipart/form-data" }); }
    @Html.DropDownList("country", ViewData["country"] as List<SelectListItem>, new { onchange = "this.form.submit();" })
    @{ Html.EndForm(); }

Accepted Answer

You are passing in ViewData["country"] object of type IEnumerable<Region> while in View you are casting it to IEnumerable<SelectListItem> which won't work obviously in action change FillCountry() to make SelectList:

public void FillCountry()
    {
        List<Region> li = new List<Region>();
        var para = new DynamicParameters();
        para.Add("@Type", 1);
        var result = con.Query<Region>("Sp_MVCDapperDDl", para, commandType: CommandType.StoredProcedure);
        var list = new SelectList(result,"CountryId","CountryName");
    }

and in View now cast it to SelectList:

@Html.DropDownList("country", ViewData["country"] as SelectList, new {onchange = "this.form.submit();" })

This will get you going.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why