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 --")
%>