Set a default value for a dropdownlist from a list

2019-09-08 05:05发布

问题:

I have this web page which shows the property of an object so that I may edit it, and I populate a DropDownListwith strings coming from another class.

Here's the method I use to populate the DropDownList:

private void PopulateOBJSetDropdownList(object selectedobj = null)
        {
            List<string> listOBJSetName = m_OBJSetManager.GetListOBJSets().OrderBy(x => x.m_Name)
                                                           .Select(x => x.m_Name.ToString())
                                                           .Distinct()
                                                           .ToList();
            ViewBag.objSetID = new SelectList(listOBJSetName );
        }

The ViewBagproperty does its job quite well, but the list comes empty when editing the item.

I'm pretty sure it is because of this line:

<div class="editor-label">
            @Html.LabelFor(model => model.m_OBJSetID, "Obj Set")
        </div>
        <div class="editor-field">
            @Html.DropDownList("objSetID ", String.Empty)
            @Html.ValidationMessageFor(model => model.m_OBJSetID)
        </div>

Because the dropdownlist is populated with String.Empty. This comes from a controller of objs.

Basically, I want this DropDownList to show me all the names of the objSets available, but I would also want it to have the correct objSet selected by default when editing an obj.

Does anyone can help? Am I clear enough? Thank you everyone.

回答1:

i would avoid the viewbag. you might want to create a view model, and pass that instead. but this can be done with the viewbag as well.

first, on your view, i would change your dropdown to the following

@Html.DropDownListFor(model => model.m_OBJSetID, DDLSelectitemListGoesHere)

if you do a view model, you can contain everything this page needs to use in one class, and send it to the view

public class MyViewModel{
    public List<YourModel> theModel { get; set; }
    public IEnumerable<SelectListItem> DDLItems { get; set; }
}

then on your view, at the top

@model PROJECTNAME.NAMESPACE.MyViewModel

and you can fill in the drop down like so

@Html.DropDownListFor(model => model.theModel.m_OBJSetID, model.DDLItems)

hopefully one of those will get you through