Html.DropDownList selected value not working using ViewBag

后端 未结 5 1136
谎友^
谎友^ 2021-01-05 20:10

Well, after a couple hours reading stuff over here, trying unsuccessfully all the solutions, also found this article that i thought it would save my life... nothing.

<
5条回答
  •  庸人自扰
    2021-01-05 20:37

    I know its an old question, but I will share another solution since sometimes you have done anything correctly, but you can't see the selected value after a request and response, since your razor has bug maybe. In this condition, that I've had, you can use select-option using viewbag:

    In controller I had:

     ViewBag.MyData = GetAllData(strSelected);
    ... 
    

    and as a private function in controller I had:

      private List GetAllData(List selectedData)
        {
    
            return MyGetAll().Select(x =>
                new SelectListItem
                {
                    Text = x.Point,
                    Value = x.Amount.ToString(),
                    Selected = selectedPrizes.Contains(x.Amount.ToString())
                })
                .ToList();
        }  
    

    And in .cshtml I had:

    
    

    I hope it will be useful for similar problems :)

提交回复
热议问题