Dropdown in MVC

后端 未结 6 711
甜味超标
甜味超标 2020-12-06 15:22

In my MVC application, I need to add a dropdown that would show a list of domain names.

I already have a ViewModel that contains multiple properties. I am not sure w

6条回答
  •  盖世英雄少女心
    2020-12-06 15:34

    1) Add a new property to my ViewModel? What should be the type? List?

    You need 2 properties to be more precise: an IEnumerable to hold all the available options and a scalar property to hold the selected value

    2) Define a method that populates the above property with values.

    Yes.

    3) Use that property in the View? Use HTML.DropdownFor?

    No, not in the view. The view doesn't call any methods. A view works with the view model. It is the responsibility of the controller to pass a properly filled view model to the view.

    So for example:

    public class MyViewModel
    {
        public string SelectedValue { get; set; }
        public IEnumerable Values { get; set; }
    
        ... some other properties that your view might need
    }
    

    and then a controller action that will populate this view model:

    public ActionResult Index()
    {
        var model = new MyViewModel();
        model.Values = new[]
        {
            new SelectListItem { Value = "1", Text = "item 1" },
            new SelectListItem { Value = "2", Text = "item 2" },
            new SelectListItem { Value = "3", Text = "item 3" },
        };
        return View(model);
    }
    

    and finally the strongly typed view in which you will display the dropdown list:

    @model MyViewModel
    @Html.DropDownListFor(x => x.SelectedValue, Model.Values)
    

    UPDATE:

    According to your updated question you are have an IEnumerable property on your view model to which you are trying to assign a value of type IEnumerable which obviously is impossible. You could convert this to an IEnumerable like this:

    var domains = FetchAllDomains().Select(d => new SelectListItem
    {
        Value = d.DomainName,
        Text = d.DomainName
    });
    return new EmailModel { DomainList = domains };
    

提交回复
热议问题