简体   繁体   中英

ASP.Net MVC Dropdown text generation using a Select List not populating the values and text

Using the following code i generate a select list in my controller and feed it into my view model.

var SelectListItems = om_repo.List().Select(x => {
            var item = new SelectListItem();
            item.Value = x.id.ToString();
            item.Text = x.code;
            return item;
        });

createvm.allOccupations = new SelectList(SelectListItems);

Here is my view code

@Html.DropDownListFor(model => model.selectedOccupation,  Model.allOccupations, "Choose one")

The output im getting is

<option>System.Web.Mvc.SelectListItem</option>

Why isnt it picking up the select list items Text and Values that are being fed. In my debugger i can see the values are set in the locals under text and value.

在此处输入图片说明

Because the DropDownlist doesn't want a SelectList ; it wants an IEnumerable of SelectListItems .

Try just:

createvm.allOccupations = SelectListItems;

Model Class also needs to be:

public IEnumerable<SelectListItem> allOccupations { get; set; }

Not

public SelectList allOccupations { get; set; }

Scott Allen expanded on the problem here: https://odetocode.com/Blogs/scott/archive/2010/01/18/drop-down-lists-and-asp-net-mvc.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM