如何从数据库中检索数据并在mvc中的下拉列表中显示

时间:2012-10-05 05:20:22

标签: asp.net-mvc

我想从数据库中检索数据并在下拉列表中显示。我使用了模型,所以我也可以从模型中获取。但它没有正确检索。如果在数据库4条目中表示它显示4个下拉按钮但在下拉列表中没有值。任何人都可以帮我解决这个问题吗?

我在视野中的代码

      <div class="editor-label">
    <%: Html.Label("Basic Qualification")%>
    </div>
    <div class="editor-field">

    <div id="basic-qualification-container1" style="margin-bottom:4px;" class="basic-qualification-container left">
           <% if (ViewData["BasicQualificationDegrees"]!=null){ %>
           <% for (int i=0; i < Model.CandidateQualifications.Count();i++) {%>

                        <%: Html.DropDownList("BasicQualificationDegree1", new SelectList((IEnumerable<Dial4Jobz.Models.Degree>)ViewData["CandidateBasicQualifications"], "Id", "Name", (IEnumerable<int>)ViewData["BasicQualificationDegrees"]), new { @class = "qualification" })%> 
                        <%: Html.TextBox("BasicQualificationSpecialization1", "", new { @title = "Enter basic qualification degree", @class="specialization" })%> 
                <%} %>  
            <%} else { %>
                <select id="BasicQualificationDegree1" name="BasicQualificationDegrees"></select>
            <%} %>
         </div>
         <div class="left">               
         <input type="button" id="btnAddBasicQualification" value="Add" />
         <input type="button" id="btnDelBasicQualification" value="Remove" />
         </div>
         </div>       

1 个答案:

答案 0 :(得分:1)

根据你的问题,

 <% for (int i=0; i < Model.CandidateQualifications.Count();i++) {%>
这是什么?你为什么算上viewdata?

<强>代码      &lt;%if(ViewData [“BasicQualificationDegrees”]!= null){%&gt;

 <% var containerId = "basic-qualification-container" + i.ToString(); %>
                      <div id="<%: containerId %>" style="margin-bottom:4px;" class="basic-qualification-container left">
                          <%: Html.DropDownList("BasicQualificationDegree" + i.ToString(), new SelectList((IEnumerable<Dial4Jobz.Models.Degree>)ViewData["CandidateBasicQualifications"], "Id", "Name", basicQualifications.ElementAt(i-1).DegreeId), new { @class = "qualification" })%> 
                           <%: Html.TextBox("BasicQualificationSpecialization" + i.ToString(), basicQualifications.ElementAt(i-1).Specialization, new { @title = "Enter basic qualification degree", @class = "specialization" })%> 
                       </div>
                 <% } %>  
             <% } else { %>
                    <div id="basic-qualification-container1" style="margin-bottom:4px;" class="basic-qualification-container left">
                        <%: Html.DropDownList("BasicQualificationDegree1", new SelectList((IEnumerable<Dial4Jobz.Models.Degree>)ViewData["CandidateBasicQualifications"], "Id", "Name"), new { @class = "qualification" })%> 
                        <%: Html.TextBox("BasicQualificationSpecialization1", "", new { @title = "Enter basic qualification degree", @class = "specialization" })%> 
                    </div>

希望它有所帮助!