MVC Dropdownlistfor<>

后端 未结 4 776
小鲜肉
小鲜肉 2021-02-10 14:37

I just started a project in MVC. I am new to MVC asp.net. I want to add a dropdown list box like I used to add in asp.net.

code glimpses in asp.net for Dropdownlist box

4条回答
  •  执念已碎
    2021-02-10 15:29

    The values for the dropdownlist should be in your existing view model:

    public class WhateverViewModel
    {
        // All of your current viewmodel fields here
        public string SelectedCity { get; set; }
        public Dictionary CityOptions { get; set; }
    }
    

    Populate these in your controller with whatever values you want (where SelectedCity is your numerical ID), then do the following in your view:

    @Html.DropDownListFor(m => m.SelectedCity,
        new SelectList(Model.CityOptions, "Key", "Value", Model.SelectedCity))
    

    If your values never change, you could hardcode them as a static member of your view model and then do:

    @Html.DropDownListFor(m => m.SelectedCity,
        new SelectList(WhateverViewModel.CityOptions, "Key", "Value", Model.SelectedCity))
    

    Either way, this is data for this view, so it belongs in your view model. If you're not using view models and this view is directly tied to a domain entity; you should be using them and now is as good a time as any to start.

提交回复
热议问题