C# Html.DropDownList 选定值不起作用(使用构造函数和 IEnumerable<SelectListItem>)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19566560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:18:45  来源:igfitidea点击:

Html.DropDownList Selected Value Not Working (Using Constructor with IEnumerable<SelectListItem>)

c#asp.net-mvcasp.net-mvc-4razorselectedvalue

提问by Paul Peat

I have an issue where the selected value is not working for the Html.DropDownList helper method. See below:

我有一个问题,即所选值不适用于 Html.DropDownList 帮助程序方法。见下文:

This is My Controller:

这是我的控制器:

public ActionResult Edit(int id = 0)
{
    NewsEvent item = GetItem(id);
    ViewBag.NewsItemId = new SelectList(ViewBag.NewsItemId.Items, "Id", "Name", item.NewsItemId);

    return View(item);
}

This is my View:

这是我的观点:

@Html.DropDownList("NewsItemId",ViewBag.NewsItemId as SelectList, string.Empty,
                           new { @class = "form-control" })

However when I try the below in by view it works:

但是,当我按视图尝试以下操作时,它会起作用:

@Html.DropDownList("NewsItemId", string.Empty)

The below also works but since the field name does not match the model, it will not post correctly.

以下也有效,但由于字段名称与模型不匹配,因此无法正确发布。

@Html.DropDownList("NewsItemIdDrop",ViewBag.NewsItemId as SelectList, string.Empty,
                           new { @class = "form-control" })

The reason I need to use the first option is so that I can add the class attribute to the control.

我需要使用第一个选项的原因是我可以将 class 属性添加到控件中。

Could someone help me understand what I am doing wrong?

有人可以帮助我了解我做错了什么吗?

采纳答案by freshbm

You have the same problem here:

你在这里有同样的问题:

DropDownListFor Not Selecting Value

DropDownListFor 未选择值

Problem is in your ViewBag property name. Because it is same as your property in Model it will not work. You should just change name of your ViewBag prop to something else, like:

问题出在您的 ViewBag 属性名称中。因为它与模型中的属性相同,所以它不起作用。您应该将 ViewBag 道具的名称更改为其他名称,例如:

ViewBag.NewsItemList = new SelectList(ViewBag.NewsItemId.Items, "Id", "Name", item.NewsItemId);

and on View

并在查看

@Html.DropDownList("NewsItemId",ViewBag.NewsItemList as SelectList, string.Empty,
                           new { @class = "form-control" })

回答by Réda Mattar

First of all, how do you populate ViewBag.NewsItemId.Items? We don't see where the values come from.

首先,你如何填充ViewBag.NewsItemId.Items?我们看不到这些值的来源。

In order to make a selected value work, it must be of the same type as the elements of your collections. If item.NewsItemIdis of type T, ViewBag.NewsItemId.Itemsmust be of type IEnumerable<T>(or any other collection type implementing it). It does not seem to be the case, because you set NewsItemIdas the selected value while your collection is based on NewsItemId.Itemswhich may not be of the same type.

为了使选定的值起作用,它必须与集合的元素具有相同的类型。如果item.NewsItemId是 type T,则ViewBag.NewsItemId.Items必须是 type IEnumerable<T>(或实现它的任何其他集合类型)。情况似乎并非如此,因为您设置NewsItemId为选定值,而您的集合所基于的NewsItemId.Items可能不是同一类型。

回答by Tracy P

I did not like the fact that you can use

我不喜欢你可以使用的事实

@Html.DropDownList("NewsItemID") 

and it works. Then you need to add the 'class' attribute and suddenly it breaks. I saw one place working and another not working using the syntax

它有效。然后你需要添加 'class' 属性,它突然中断了。我看到一个地方工作,另一个地方不工作使用语法

@Html.DropDownList("NewsItemId",ViewBag.NewsItemId as SelectList, string.Empty,
                       new { @class = "form-control" })

When I researched this, I determined the ViewBag.NewsItemId was actually a null in the view. So a working syntax, with the Model and ViewBag fields having the same name is

当我研究这个时,我确定 ViewBag.NewsItemId 在视图中实际上是一个空值。因此,具有相同名称的 Model 和 ViewBag 字段的工作语法是

@Html.DropDownList("NewsItemId", null, string.Empty,
                       new { @class = "form-control" })

回答by Juho Honkala

I tried lot of stuff but eventually got it working like this

我尝试了很多东西,但最终让它像这样工作

In controller

在控制器中

int valittu_tila = 1;
var tapahtumantilat = new List<SelectListItem>();

tapahtumantilat.Add(new SelectListItem { Text = "Tapahtumaa kirjataan", Value = "0" });
tapahtumantilat.Add(new SelectListItem { Text = "Odottaa jonossa", Value = "1"});
tapahtumantilat.Add(new SelectListItem { Text = "Tapahtumaa k?sitell??n", Value = "2"});

ViewBag.tilalista = new SelectList(tapahtumantilat, "Value", "Text", valittu_tila);

And then in view I just put (I have the onchange event and class for dropdown too here but you can remove those if you want).

然后在视图中我只是放了(我在这里也有下拉列表的 onchange 事件和类,但如果你愿意,你可以删除它们)。

@Html.DropDownList("tuki_tila", ViewBag.tilalista as SelectList, "-- valitse tila --", new { @onchange = "executeticketsearch();", @class = "haku_dropdowns" })

(Sorry about finnish in the text values and variable names, but those shouldn't matter :D)

(对不起,文本值和变量名称中的芬兰语,但这些应该无关紧要:D)

回答by user241841

You should change the very name of the field of your DropDownList:

您应该更改 DropDownList 字段的名称:

@Html.DropDownList("Some_Name_that_does_not_exist_in_model", ViewBag.NewsItemId as SelectList, string.Empty, new { @class = "form-control" })

回答by Seliya Hilal

change viewbag property name to other then model variable name used on page.

将 viewbag 属性名称更改为页面上使用的其他模型变量名称。

回答by Seliya Hilal

@Html.DropDownList("NewsItemId",ViewBag.NewsItemId as SelectList, string.Empty,
    new { @class = "form-control" })

change to

改成

@Html.DropDownList("NewsItemId", ViewBag.NewsItemIdList as SelectList, string.Empty, 
    new { @class = "form-control" })

ViewBag.NewsItemIdListname changed. also change in controller.

ViewBag.NewsItemIdList名字变了。控制器也发生了变化。

回答by Pablo Alejandro Perez Acosta

I had the same problem. In the example below The variable ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] has a SelectListItem list with a default selected value but such attribute is not reflected visually.

我有同样的问题。在下面的示例中,变量 ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] 具有一个 SelectListItem 列表,该列表具有默认选定值,但此类属性未在视觉上反映出来。

// data 
        var p_estadoAcreditacion = "NO";
        var estadoAcreditacion = new List<SelectListItem>();
        estadoAcreditacion.Add(new SelectListItem { Text = "(SELECCIONE)"    , Value = " "    });
        estadoAcreditacion.Add(new SelectListItem { Text = "SI"              , Value = "SI"   });
        estadoAcreditacion.Add(new SelectListItem { Text = "NO"              , Value = "NO"   });

        if (!string.IsNullOrEmpty(p_estadoAcreditacion))
        {
            estadoAcreditacion.First(x => x.Value == p_estadoAcreditacion.Trim()).Selected = true;
        }
         ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] = estadoAcreditacion;

I solved it by making the first argument of DropdownList, different to the id attribute.

我通过使 DropdownList 的第一个参数与 id 属性不同来解决它。

// error:
@Html.DropDownList("SELECT__ACREDITO_MODELO_INTEGRADO"
, ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] as List<SelectListItem>
, new
{
id         = "SELECT__ACREDITO_MODELO_INTEGRADO"
...
// solved :
@Html.DropDownList("DROPDOWNLIST_ACREDITO_MODELO_INTEGRADO"
, ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] as List<SelectListItem>
, new
{
id         = "SELECT__ACREDITO_MODELO_INTEGRADO"
...