I would suggest that you use strongly typed views (without the need for ViewData and magic strings). As always, start by defining the model class of the view:
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) {
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 do not select the country, but when you pass the id this action, for example /home/index/2 , you get the country with the selected identifier.
Note. If you are using ASP.NET MVC 1.0, you will not have the strongly typed DropDownListFor helper, and you can use it instead:
<%= Html.DropDownList( "SelectedCountryId", Model.Countries, "-- Select Country --") %>
source share