Create DropDownListFor from SelectList with default value

前端 未结 5 1210
花落未央
花落未央 2021-01-05 08:33

I have a dropdownlistfor:

 @Html.DropDownListFor(model => model.Item.Item.Status, new SelectList(@Model.AllStatus, \"id\", \"Description\"),          


        
5条回答
  •  执念已碎
    2021-01-05 08:38

    I ended up using a variant of thomasjaworski's answer.

    View:

    @Html.DropDownListFor(model => model.SelectedStatusIndex, new SelectList(@Model.StatusSelectList, "Value", "Text"), new { id = "statusDropdown" })
    

    ViewModel constructor

            StatusSelectList = AllStatus.Select(x =>
                                            new StatusSelectListItem
                                            {
                                                Text = x.Description,
                                                Value = x.id.ToString()
                                            }).ToList();
    
            this.SelectedStatusIndex = 2;//Default Status is New
    

    Controller on HTTP POST

    I set model.Item.Item.Status seperately from the dropdown itself:

    model.Item.Item.Status = model.SelectedStatusIndex;
    

    because the dropdown set's the value of the expression passed as the first argument:

    @Html.DropDownListFor(model => model.SelectedStatusIndex, new SelectList(@Model.StatusSelectList, "Value", "Text"), new { id = "statusDropdown" })
    

    In this case model.SelectedStatusIndex is what is set by the dropdown. This controller implementation is what I found to be tricky.

提交回复
热议问题