asp.net-mvc DropDownListFor 未选择值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2278056/
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-09-08 00:08:53  来源:igfitidea点击:

DropDownListFor Not Selecting Value

asp.net-mvc

提问by senfo

I'm using the DropDownListFor helper method inside of an edit page and I'm not having any luck getting it to select the value that I specify. I noticed a similar questionon Stackoverflow. The suggested workaround was to, "populate your SelectList in the view code". The problem is that I've already tried this and it's still not working.

我在编辑页面内使用 DropDownListFor 助手方法,但我没有运气让它选择我指定的值。我在 Stackoverflow 上注意到了一个类似的问题。建议的解决方法是“在视图代码中填充您的 SelectList”。问题是我已经尝试过这个,但它仍然无法正常工作。

<%= Html.DropDownListFor(model => model.States, new SelectList(Model.States.OrderBy(s => s.StateAbbr), "StateAbbr", "StateName", Model.AddressStateAbbr), "-- Select State --")%>

I have set a breakpoint and have verified the existence (and validity) of model.AddressStateAbbr. I'm just not sure what I'm missing.

我已经设置了一个断点并验证了 model.AddressStateAbbr 的存在(和有效性)。我只是不确定我错过了什么。

回答by wut-excel

After researching for an hour, I found the problem that is causing the selected to not get set to DropDownListFor. The reason is you are using ViewBag's name the same as the model's property.

经过一个小时的研究,我发现了导致所选对象未设置为DropDownListFor. 原因是您使用的 ViewBag 名称与模型的属性相同。

Example

例子

public  class employee_insignia
{ 
   public int id{get;set;}
   public string name{get;set;}
   public int insignia{get;set;}//This property will store insignia id
}

// If your ViewBag's name same as your property name 
  ViewBag.Insignia = new SelectList(db.MtInsignia.AsEnumerable(), "id", "description", 1);

View

看法

 @Html.DropDownListFor(model => model.insignia, (SelectList)ViewBag.Insignia, "Please select value")

The selected option will not set to dropdownlist, BUT When you change ViewBag's name to different name the selected option will show correct.

所选选项不会设置为下拉列表,但是当您将 ViewBag 的名称更改为其他名称时,所选选项将显示正确。

Example

例子

ViewBag.InsigniaList = new SelectList(db.MtInsignia.AsEnumerable(), "id", "description", 1);

View

看法

 @Html.DropDownListFor(model => model.insignia, (SelectList)ViewBag.InsigniaList , "Please select value")

回答by BnWasteland

Try:

尝试:

<%= Html.DropDownListFor(
    model => model.AddressStateAbbr,
    new SelectList(
        Model.States.OrderBy(s => s.StateAbbr),
        "StateAbbr",
        "StateName",
        Model.AddressStateAbbr), "-- Select State --")%>

or in Razor syntax:

或在 Razor 语法中:

@Html.DropDownListFor(
    model => model.AddressStateAbbr,
    new SelectList(
        Model.States.OrderBy(s => s.StateAbbr),
        "StateAbbr",
        "StateName",
        Model.AddressStateAbbr), "-- Select State --")

The expression based helpers don't seem to respect the Selected property of the SelectListItems in your SelectList.

基于表达式的助手似乎不尊重 SelectList 中 SelectListItems 的 Selected 属性。

回答by Chad Hedgcock

If you're doing it properly and using a model--unlike all these ViewBag weirdos--and still seeing the issue, it's because @Html.DropDownListFor(m => m.MyValue, @Model.MyOptions)can't match MyValuewith the choices it has in MyOptions. The two potential reasons for that are:

如果您做得正确并使用模型——与所有这些 ViewBag 怪人不同——并且仍然看到问题,那是因为@Html.DropDownListFor(m => m.MyValue, @Model.MyOptions)无法与MyValue它在MyOptions. 造成这种情况的两个潜在原因是:

  1. MyValueis null. You haven't set it in your ViewModel. Making one of MyOptionshave a Selected=truewon't solve this.
  2. More subtly, the typeof MyValueis different than the types in MyOptions. So like, if MyValueis (int) 1, but your MyOptionsare a list of padded strings {"01", "02", "03", ...}, it's obviously not going to select anything.
  1. MyValue一片空白。您尚未在 ViewModel 中设置它。让一个MyOptions拥有一个Selected=true不会解决这个问题。
  2. 更微妙的是, 的类型MyValue中的类型不同MyOptions。所以,如果MyValue(int) 1,但你MyOptions是一个填充字符串列表{"01", "02", "03", ...},它显然不会选择任何东西。

回答by fiat

While not addressing this question - it may help future googlers if they followed my thought path:

虽然没有解决这个问题 - 如果他们遵循我的想法,它可能会对未来的谷歌员工有所帮助:

I wanted a multiple select and this attribute hack on DropDownListForwasn't auto selecting

我想要一个多选,并且DropDownListFor上的这个属性 hack不是自动选择

Html.DropDownListFor(m => m.TrainingLevelSelected, Model.TrainingLevelSelectListItems, new {multiple= "multiple" })

instead I should have been using ListBoxForwhich made everything work

相反,我应该使用ListBoxFor使一切正常

Html.ListBoxFor(m => m.TrainingLevelSelected, Model.TrainingLevelSelectListItems)

回答by Prageeth godage

I also having similar issue and I solve it by as follows, set the

我也有类似的问题,我按如下方式解决,设置

model.States property on your controller to what you need to be selected

控制器上的 model.States 属性为您需要选择的内容

model.States="California"

model.States="加利福尼亚"

and then you will get "California" as default value.

然后您将获得“加利福尼亚”作为默认值。

回答by Seliya Hilal

this problem is common. change viewbag property name to other then model variable name used on page.

这个问题很常见。将 viewbag 属性名称更改为页面上使用的其他模型变量名称。

回答by BMills

One other thing to check if it's not all your own code, is to make sure there's not a javascript function changing the value on page load. After hours of banging my head against a wall reading through all these solutions, I discovered this is what was happening with me.

检查它是否不是您自己的所有代码的另一件事是确保没有 javascript 函数更改页面加载时的值。经过几个小时的敲击墙壁阅读所有这些解决方案后,我发现这就是发生在我身上的事情。

回答by JuanR

I encountered this issue recently. It drove me mad for about an hour. In my case, I wasn'tusing a ViewBagvariable with the same name as the model property.

我最近遇到了这个问题。这让我疯狂了大约一个小时。就我而言,我没有使用ViewBag与模型属性同名的变量。

After tracing source control changes, the issue turned out to be that my actionhad an argument with the same nameas the model property:

跟踪源代码控制更改后,问题原来是我的操作有一个模型属性同名参数

public ActionResult SomeAction(string someName)
{
    var model = new SomeModel();
    model.SomeNames = GetSomeList();
    //Notice how the model property name matches the action name
    model.someName = someName; 
}

In the view:

在视图中:

@Html.DropDownListFor(model => model.someName, Model.SomeNames)

I simply changed the action's argument to some other name and it started working again:

我只是将动作的参数更改为其他名称,然后它又开始工作了:

public ActionResult SomeAction(string someOtherName)
{
    //....
}

I suppose one could also change the model's property name but in my case, the argument name is meaningless so...

我想也可以更改模型的属性名称,但就我而言,参数名称毫无意义,所以......

Hopefully this answer saves someone else the trouble.

希望这个答案可以为其他人省去麻烦。

回答by jNi

The issue at least for me was tied to the IEnumerable<T>.

至少对我来说,这个问题与IEnumerable<T>.

Basically what happened was that the view and the model did not have the same reference for the same property.

基本上发生的事情是视图和模型对相同的属性没有相同的引用。

If you do this

如果你这样做

IEnumerable<CoolName> CoolNames {get;set;} = GetData().Select(x => new CoolName{...});}

Then bind this using the

然后使用

@Html.DropDownListFor(model => model.Id, Model.CoolNames)

The View loses track of the CoolNames property, a simple fix is just to add .ToList()After dooing a projection (.Select()) ;).

View 失去了 CoolNames 属性的踪迹,一个简单的解决方法是添加.ToList()After dooing a projection ( .Select()) ;)。

回答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"

...

...