I was able to create a dropdownlist for my MVC project, but the value is not selected as selected value on the dropdownlist. It just shows whole county list from the first.The value is from database. I tried find it from previous post, but it was quite confusing. Please, suggest me for any idea.
Controller Code
public ActionResult Edit(int i)
{
var items = new SelectList(db.MST_COUNTRies.ToList(), "COUNTRY_ID", "COUNTRY_NM");
ViewData["MST_COUNTRies"] = items;
}
View Code
<%= Html.DropDownList("COUNTRY_ID", (SelectList)ViewData["MST_COUNTRies"])%>
I would suggest you using a strongly typed views (no need of ViewData
and magic strings). As always start by defining your view model class:
public class CountriesViewModel
{
public int? SelectedCountryId { get; set; }
public IEnumerable<SelectListItem> Countries { get; set; }
}
Then your controller:
public class HomeController : Controller
{
public ActionResult Index(int? id)
{
// TODO: Fetch those from your DB
var countries = new[]
{
new { Id = 1, Name = "Country 1" },
new { Id = 2, Name = "Country 2" },
};
var model = new CountriesViewModel
{
Countries = new SelectList(countries, "Id", "Name", id)
};
return View(model);
}
}
And finally your strongly typed view:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<SomeNs.Models.CountriesViewModel>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%= Html.DropDownListFor(
x => x.SelectedCountryId,
Model.Countries,
"-- Select Country --")
%>
</asp:Content>
Now when you call /home/index
you get no country selected, but when you pass the id
to this action like /home/index/2
you get the country with this id selected.
Remark: If you are using ASP.NET MVC 1.0 you won't have the strongly typed DropDownListFor helper and you could use this instead:
<%= Html.DropDownList(
"SelectedCountryId",
Model.Countries,
"-- Select Country --")
%>
Try something like this:
public ActionResult Edit(int i)
{
var items = new SelectList(db.MST_COUNTRies.ToList(), "COUNTRY_ID", "COUNTRY_NM", yourSelectedCountryId);
ViewData["COUNTRY_ID"] = items;
}
Then in your view:
<%= Html.DropDownList("COUNTRY_ID"); %>
Some notes:
- The "yourSelectedCountryId" argument in new SelectList() can be used to determine the item that should be initially selected. Assuming that COUNTRY_ID is an int, this argument should also be an int.
- If you populate ViewData with an IEnumerable that matches the name/id of the DropDownList, the Html.DropDownList() call automatically finds it and uses it. That's why I changed ViewData["MST_COUNTRies"] to ViewData["COUNTRY_ID"]. It saves a little code, and I found myself forced to use this approach to work around a bug in MVC v1.