I've found many posts regarding the same questions but none of them were with view data and connected with a repository. I need to use only one class no separate class for Countries
and Gender
, please.
Error:
Controller
[HttpGet]
public ActionResult Member(int? MemberId)
{
if (MemberId == null)
{
Member m = new Member();
ViewData["CountriesList"] = _dal.GetCountryList();
ViewData["GenderList"] = _dal.GetGenderList();
return View(m);
}
var data = _dal.GetMemberData(MemberId);
if (data == null)
{
return View();
}
return View(data);
}
Class
public string Country { get; set; }
public string Gender { get; set; }
public string Address { get; set; }
public int Phone { get; set; }
public IEnumerable<SelectListItem> _CountriesList { get; set; }
public IEnumerable<SelectListItem> _GenderList { get; set; }
View
<div class="col-md-8">
<div class="col-md-4">
<label id="country">Country</label>
@Html.DropDownListFor(m => m.Country, Model._CountriesList, ViewData["CountriesList"] as IEnumerable<SelectListItem>, new { @class = "form-control", placeholder = "-- Select Country --" })
</div>
<div class="col-md-4">
<label id="gender">Gender</label><br />
@Html.DropDownListFor(m => m.Gender, Model._GenderList, ViewData["GenderList"] as IEnumerable<SelectListItem>, new { @class = "form-control", placeholder = "-- Select Gender --" })
</div>
</div>
Repository
[public IEnumerable<SelectListItem> GetCountryList()
{
var _country = new List<SelectListItem>();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("sp_CountryList", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Flag", "getCountryList");
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
_country.Add(new SelectListItem { Text = sdr["CountryName"].ToString(), Value = sdr["rowId"].ToString() });
}
con.Close();
}
return _country;
}]
It seems you are trying to set two datasources to DropDownList at same time which are Model._CountriesList
and ViewData["CountriesList"]
and it causes build error. There is no such a overload method of DropDownListFor
, you have to choose one of them ViewBag
or Model
.
As I understood correctly, you don't need to use _CountriesList
or _GenderList
so just remove Model._CountriesList
since you use ViewBag
:
<div class="col-md-8">
<div class="col-md-4">
<label id="country">Country</label>
@Html.DropDownListFor(m => m.Country, ViewData["CountriesList"] as IEnumerable<SelectListItem>, new { @class = "form-control", placeholder = "-- Select Country --" })
</div>
<div class="col-md-4">
<label id="gender">Gender</label><br />
@Html.DropDownListFor(m => m.Gender, ViewData["GenderList"] as IEnumerable<SelectListItem>, new { @class = "form-control", placeholder = "-- Select Gender --" })
</div>
</div>
For more info, have a look at overloads of DropDownListFor