开发者

DropDownListFor does not select value if in for loop

开发者 https://www.devze.com 2022-12-26 12:46 出处:网络
In my view <%= Html.DropDownListFor( x => x.Countries[ i ], Model.CountryList )%> in my controller

In my view

<%= Html.DropDownListFor( x => x.Countries[ i ], Model.CountryList )%>

in my controller

public int[ 开发者_C百科] Countries { get; set; }

public List<SelectListItem> CountryList { get; set; }

When the forms gets posted there is no problem, the dropdown is populated and the values the user selects are posted. But when I try to load the form with already assigned values to the Countries[ ] it does not get selected.


Not sure if this is new to mv4 or if it exists in prior version. But the DropDownListFor includes an additional parameter for the SelectList Constructor.

SelectList(IEnumerable, String, String, Object)

For example:

Html.DropDownListFor( x => x.Countries[ i ], New SelectList(Model.CountryList,"ID","Description",Model.Countries[i]))

Where ID is the Country ID in the CountryList object and Description is the Country Name.


I'm getting the same too. When using foreach to loop around a DropDownListFor (i.e. to render multiple select elements on a page).

My work around is to set the selected value in the controller rather than the view: something like this:

In the controller:

public class FruitList 
{        
    public int? selectedFruit{ get; set; }
    public List<SelectListItem> fruits
    {
        get
        {
            fruitEntities F = new fruitEntities();
            List<SelectListItem> list = (from o in F.Options
                                         select new SelectListItem
                                         {
                                             Value = o.fruitID,
                                             Text = o.fruit,                                                 
                                             Selected = o.fruitID == selectedFruit
                                         }).ToList();
            return list;
        }
    }
}

public class ViewModel 
{              
    public List<FruitList> collectionOfFruitLists { get; set; }        
}

In the view

<table>                        
   <% for (int i=0; i < Model.collectionOfFruitLists.Count; i++ )
        { %>
        <tr>                            
            <td><%: Html.DropDownList("fruitSelectList", collectionOfFruitLists[i].fruits, "Please select...") %></td>                
        </tr>
        <%} %>
 </table>

The nifty bit is Selected = o.fruitID == selectedFruit in the controller which acts like a SQL CASE statement; this is really well explained by Lance Fisher (thanks Lance, your post really helped me out :)


I know this question is a bit old but I just came across this problem with looping through a list of objects and attempting to bind the values to DropDownListFor(s) in my Edit View.

I overcame the issue with an inline solution by using the logic from some of the previous solutions given by others for this question.

Binding to my Model:

@Html.DropDownListFor(model => model.QuestionActions[i].QuestionActionTypeId,
      Model.QuestionActionTypes.Select(x => new SelectListItem() { Value = x.Value, Text = x.Text, Selected = (x.Value == Model.QuestionActions[i].QuestionActionTypeId.ToString()) }).ToList(),
          "Select Action Type",
                 new { })

Model.QuestionActionTypes is a SelectList that is populated in my Controller.


This is a bit of a hack, and JavaScript reliant but it worked very well for me.

You'll need to know the client IDs that will be produced by the fields (usually these can be worked out manually but for safety you may want to use something like a FieldIDFor method.

You just need to set the values based on the model, in jQuery's $(document).ready:

<script type="text/javascript">
    $(document).ready(function () {
        @for(var i = 0; i < 5; i++)
        {
            <text>
                $("#@Html.FieldIDFor(m => m.Countries[i])").val("@Model.Countries[i]");
            </text>
        }
    });
</script>


A select box sends a single value, so the Countries property should not be an array. Also in your post it is not clear where's the i variable you are using in your lambda expression coming from and this x.CountryList used in the helper won't compile as x is not defined.

Model:

public class MyModel
{
    public int SelectedCountry { get; set; }
    public List<SelectListItem> CountryList { get; set; }
}

View:

<%= Html.DropDownListFor(x => x.SelectedCountry, Model.CountryList) %>

UPDATE:

According to the comment it seems that there are multiple drop downs. I suspect that the problem might come from the i variable used as index in a for loop.

You might try this instead:

Model:

public class MyModel
{
    public int[] Countries { get; set; }
    public List<SelectListItem> CountryList { get; set; }
}

View:

<% foreach (var country in Model.Countries) { %>
    <%= Html.DropDownListFor(x => country, Model.CountryList) %>
<% } %>


Instead of using a IEnumerable in your viewmodel use a List of objects like this one:

public List<PairVM<string,string>> TiposValorCobertura { get; private set; }

And in your view when you assign the selectable elements for the dropdownlist in the loop, do it this way:

@Html.DropDownListFor(m => m.Coberturas[i].TipoLimiteInferior, new SelectList(Model.TiposValorCobertura,"Key","Description",  Model.Coberturas[i].TipoLimiteIferior))

Where "Key" and "Description" are PairVM's properties

0

精彩评论

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