开发者

How to get the selected value of some dropdownlist, called several times on a loop?

开发者 https://www.devze.com 2023-02-16 23:20 出处:网络
On my application, I need to display some dropdownlist, linked to a display line. <table> <% foreach (var item in Model) { %>

On my application, I need to display some dropdownlist, linked to a display line.

<table>
        <% foreach (var item in Model) { %>
                <td>
                <%= Html.Encode(item.COMPETENCE_LIBELLE) %>
            </td>
            <td>
                <%= Html.DropDownListFor(item.FK_NIVEAU_ID, (SelectList)ViewData["FK_Niveau"]%>
            </td>
<% } %>
</table>

However, I dont know why, the selected val开发者_Go百科ue of my ddlist is never displayed...

I havent got any problem to display the selected value of a single ddlist, but when its on a loop... I dont know what to do...

Any idea ?


If you need to display multiple dropdown lists then you might need to adapt your view model. So let's take an example:

public class ItemsViewModel
{
    public string Label { get; set; }
    public string SelectedId { get; set; }
    public IEnumerable<SelectListItem> Values { get; set; }
}

public class MyViewModel
{
    public IEnumerable<ItemsViewModel> Items { get; set; }
}

then have a controller action which will populate this view model:

public ActionResult Index() 
{
    var model = new MyViewModel
    {
        Items = new[]
        {
            // TODO: fetch from your repository
            new ItemsViewModel 
            { 
                Label = "label 1",
                Values = new[] 
                { 
                    new SelectListItem { Value = "1", Text = "item 1" },
                    new SelectListItem { Value = "2", Text = "item 2" }
                }
            },
            new ItemsViewModel 
            { 
                Label = "label 2",
                // Automatically preselect the second item in the ddl
                SelectedId = "B",
                Values = new[] 
                { 
                    new SelectListItem { Value = "A", Text = "foo1" },
                    new SelectListItem { Value = "B", Text = "bar" }
                }
            },
        }
    }
    return View(model);
}

and then have a corresponding strongly typed view:

<table>
    <thead> 
        <tr>
            <th>Label</th>
            <th>Values</th>
        </tr>
    </thead>
    <tbody>
        <%= Html.EditorFor(x => x.Items)
    </tbody>
</table>

and in the corresponding editor template (~/Views/Shared/EditorTemplates/ItemsViewModel.ascx):

<%@ Control 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.ItemsViewModel>" 
%>
<tr>
    <td>
        <%: Model.Label %>
    </td>
    <td>
        <%= Html.DropDownListFor(
            x => x.SelectedId, 
            new SelectList(Model.Items, "Values", "Text")
        ) %>
    </td>
</tr>
0

精彩评论

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