MVC5 Razor html.dropdownlistfor set selected when value is in array

后端 未结 3 739
旧巷少年郎
旧巷少年郎 2020-11-22 00:56

I\'m developing an ASP.NET MVC 5 application, with C# and .NET Framework 4.6.1.

I have this View:

@model MyProject.Web.API.Models.Aggreg         


        
3条回答
  •  一整个雨季
    2020-11-22 01:51

    I leave this in case it helps someone else. I had a very similar problem and none of the answers helped.

    We had in a view this line at the top:

    IEnumerable exitFromTrustDeed = (ViewData["ExitFromTrustDeed"] as IEnumerable).Select(e => new SelectListItem() { 
        Value = e, 
        Text = e,
        Selected = Model.ExitFromTrustDeed == e
    });
    

    and then below in the view:

    @Html.DropDownListFor(m => m.ExitFromTrustDeed, exitFromTrustDeed, new { @class = "form-control" })
    

    We had a property in my ViewData with the same name as the selector for the lambda expression and for some reason that makes the dropdown to be rendered without any option selected.

    We changed the name in ViewData to ViewData["ExitFromTrustDeed2"] and that made it work as expected.

    Weird though.

提交回复
热议问题