下拉列表显示 Microsoft.AspNetCore.Mvc.Rendering.SelectlistItem 而不是实际文本值

问题描述 投票:0回答:1

我的 Razor 页面上有一个下拉列表。我将下拉列表与 ViewData 绑定。下面是我的控制器的代码,我从数据库获取数据:

public async Task<IActionResult> Index()
{
    List<DocumentType> docTypes = new List<DocumentType>();
    docTypes = await _documentTypeService.GetDocumentTypes(deptId);

    ViewData["DocumentType"] = new SelectList(docTypes, "Id", "Description");
}   

这就是我显示下拉列表的方式,并且我还根据特定条件为下拉列表选择一个值。

这是视图标记:

<table class="table table-bordered">
    <thead>
        <tr>
            <th>Type</th>
    </thead>
    <tbody>     
    @if (Model != null)
    {
        @foreach (var item in Model)
        {
            string selected = String.Empty;
              
            @foreach (var code in (SelectList)ViewData["DocumentType"])
            {
                 if (code.Text.Contains("This is the test for RCA-500"))
                 {
                       selected = code.Text;
                       break;
                 }
            }
            <tr>
                <td>
                    <select class="form-control" style="min-width:150px" id="[email protected]" asp-items="@(new SelectList(ViewBag.DocumentType,selected))" asp-for="@item.DocumentType"></select>
                </td>
            </tr>

此下拉列表显示“Microsoft.AspNetCore.Mvc.Rendering.SelectlistItem”而不是实际值。不知道我做错了什么。

我尝试从 asp-items 中删除

@
符号,但随后我开始收到编译器错误,提示“;”不见了。

c# asp.net-core asp.net-core-mvc razor-pages
1个回答
0
投票

您必须提供显示文本的属性名称及其值,如下所示。

<select class="form-control" style="min-width:150px" id="[email protected]" 
    asp-items="@(new SelectList(ViewBag.DocumentType, "Value", "Text" selected))" 
    asp-for="@item.DocumentType">
</select>

但是,我相信上述方法不会以编程方式选择正确的选项,因为它将根据

DocumentType
的值绑定值。

您应该将所需的选定选项设置为

DocumentType
,而不是使用
selected
变量。

@foreach (var code in (SelectList)ViewData["DocumentType"])
{
    if (code.Text.Contains("This is the test for RCA-500"))
    {
        item.DocumentType = Convert.ToInt32(code.Value);  // Convert the `Value` to the `DocumentType` type
        break;
    }
}

<tr>
    <td>
        <select class="form-control" style="min-width:150px" id="[email protected]" 
            asp-items="@(ViewBag.DocumentType as SelectList)" 
            asp-for="@item.DocumentType">
        </select>
    </td>
</tr>
© www.soinside.com 2019 - 2024. All rights reserved.