开发者

DropDownListFor doesnt get the selected item in the view but in the viewmodel

开发者 https://www.devze.com 2023-03-31 23:25 出处:网络
Im using a dropdownlist helper for in my view like this: @Html.DropDownListFor(m => m.BasePlayerForm.Position, Model.GetPositions())

Im using a dropdownlist helper for in my view like this:

 @Html.DropDownListFor(m => m.BasePlayerForm.Position, Model.GetPositions())

I have in the model a function to populate the list:

 public IEnumerable<SelectListItem> GetPositions()
    {
        foreach (string positionValue in Enum.GetNames(typeof(PlayerPosition)))
        {
            var selectLis开发者_如何学运维tItem = new SelectListItem();
            selectListItem.Text = positionValue;
            selectListItem.Value = ((int)Enum.Parse(typeof(PlayerPosition), positionValue)).ToString();
            if (BasePlayerForm.Position.ToString() == positionValue)
                selectListItem.Selected = true;

            yield return selectListItem;
        }
    }

(I know there is a shorter version also, to return a list item, but for debugging purposes I found this more useful.) The funny part is, if I put a brakepoint at the "selectListItem.Selected = true;" row, the debugger hits it, but when I render the view, there is no option selected. I also use another dropdownlistfor helper in my view the same way to populate the dropdownlist but that one gets selected item. I really dont know whats the problem with it. If anybody knows pls let me know, I would appreciate it a lot =)


When using strongly typed Html Helpers that take an IEnumerable of SelectListItem as a parameter, the selected property of those items are ignored.

When you set the value of the SelectListItem in your GetPositions() method you are casting the PlayerPosition enum to an int. I am assuming the BasePlayerForm.Position property in your view model is not an int. If you change BasePlayerForm.Position to an int the selected item should be set based on that property.


You could, instead of using a function, use that code inside of property:

public IEnumerable<SelectListItem> ChangeMyName {  
get {  
foreach (string positionValue in Enum.GetNames(typeof(PlayerPosition)))
    {
        var selectListItem = new SelectListItem();
        selectListItem.Text = positionValue;
        selectListItem.Value = ((int)Enum.Parse(typeof(PlayerPosition), positionValue)).ToString();
        if (BasePlayerForm.Position.ToString() == positionValue)
            selectListItem.Selected = true;

        ChangeMyName.Add(selectListItem);
    }
set{return;}  
}  

Then, you could call it like this:

@Html.DropDownListFor(m => m.BasePlayerForm.Position,new SelectList( Model.GetPositions)  

I'm not sure if this helps, but this would be what I would try.

0

精彩评论

暂无评论...
验证码 换一张
取 消