ASP.NET MVC DropdownList and Selected Value

I managed to create a drop-down list for my MVC project, but the value was not selected as the selected value in the drop-down list. It just shows a complete list of the graph from the first. The value is from the database. I tried to find it from a previous post, but it was rather confusing. Please offer me 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; } 

Code view

 <%= Html.DropDownList("COUNTRY_ID", (SelectList)ViewData["MST_COUNTRies"])%> 
+1
source share
2 answers

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) { // 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 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 --") %> 
+6
source

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 opinion:

 <%= Html.DropDownList("COUNTRY_ID"); %> 

Some notes:

  • The argument "yourSelectedCountryId" in the new SelectList () element can be used to determine the element that should be initially selected. Assuming COUNTRY_ID is int, this argument should also be int.
  • If you populate the ViewData with an IEnumerable that matches the name / id of DropDownList, calling Html.DropDownList () automatically finds it and uses it. So I changed ViewData ["MST_COUNTRIES"] to ViewData ["COUNTRY_ID"]. It saves a little code, and I forced to use this approach to work with the error in MVC v1.
+1
source

All Articles