razor Html.DropdownList provide “Please select” as optionLabel AND “US” as selectedValue

后端 未结 4 1716
情话喂你
情话喂你 2021-02-01 10:21

Data:

var countries = new Dictionary();
countries.Add(\"AF\",\"Afghanistan\");
countries.Add(\"US\",\"United States\");
cou         


        
4条回答
  •  死守一世寂寞
    2021-02-01 11:17

    This should work. No idea why it doesn't because you haven't shown your actual code. Probably there's no option with key = "US" in your actual dataset.

    But anyway let me illustrate with an example the approach that I would recommend which is to use a view model and a strongly typed helper DropDownListFor helper.

    Model:

    public class CountriesViewModel
    {
        public string SelectedCountryCode { get; set; }
        public IEnumerable Countries { get; set; }
    }
    

    Controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new CountriesViewModel();
            // TODO: obviously those will come from your database
            model.Countries = new[]
            {
                new SelectListItem { Value = "AF", Text = "Afghanistan" },
                new SelectListItem { Value = "US", Text = "United States" },
                new SelectListItem { Value = "FR", Text = "France" },
            };
    
            // Preselect the option with Value = "US"
            // Make sure you have such option in the Countries list
            model.SelectedCountryCode = "US";
            return View(model);
        }
    }
    

    View (~/Views/Home/Index.cshtml):

    @model CountriesViewModel
    
    @Html.DropDownListFor(
        x => x.SelectedCountryCode,
        Model.Countries, 
        "Select Country"
    )
    

    Result:

    enter image description here

提交回复
热议问题