Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

c# - MVC DropDownListFor not selecting value from model

I have read through this question ASP.NET MVC DropDownListFor not selecting value from model and answer but I don't know the solution to my problem.

This is my view:

@foreach (var adjusterLanguages in Model.adjusterLanguages)
{
    <div class="editor-field row">
        @Html.DropDownListFor(model => Model.adjusterLanguages[i].languageID,
                              (SelectList)ViewBag.ForeignLanguages) 
        @Html.ValidationMessageFor(model =>Model.adjusterLanguages[i].languageID)
    </div>

    <div style="clear: left;"></div>

    i++;
}

I can confirm that the model data is being populated (from my controller):

model.adjusterLanguages = adjLangs;

So, how can I make it select the items when the model gets sent to the view?

The generated html is as follows:

<div class="editor-field row">
    <select id="adjusterLanguages_0__languageID" name="adjusterLanguages[0].languageID"><option value="">--Select--
        </option>
        <option value="94c5be88-814e-4719-9784-587eb88aa975">Afrikanns</option>
        <option value="37b7bf71-7f4e-47c2-8b81-652b0d63dbcb">Albanian</option>
        <option value="c94d6d85-0ba2-47d7-932e-2a61feba37b3">Arabic</option>
        <!-- ... truncated for brevity ... -->
    </select> 
    <span class="field-validation-valid" data-valmsg-for="adjusterLanguages[0].languageID" data-valmsg-replace="true"></span>
</div>
<div style="clear: left;"></div>
<div class="editor-field row">
     <select id="adjusterLanguages_1__languageID" name="adjusterLanguages[1].languageID">
          <option value="">--Select--</option>
          <option value="94c5be88-814e-4719-9784-587eb88aa975">Afrikanns</option>
          <option value="37b7bf71-7f4e-47c2-8b81-652b0d63dbcb">Albanian</option>
          <option value="c94d6d85-0ba2-47d7-932e-2a61feba37b3">Arabic</option>
          <!-- ... truncated for brevity ... -->
     </select> 
     <span class="field-validation-valid" data-valmsg-for="adjusterLanguages[1].languageID" data-valmsg-replace="true"></span>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found the answer! Thanks to all for your help. When I change my code to the following, it works. The code simply specifies the selected value:

@Html.DropDownListFor(
   model => Model.adjusterLanguages[i].languageID, 
   new SelectList(
       ViewBag.ForeignLanguages, "Value", "Text", 
       @Model.adjusterLanguages[i].languageID)) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...