Asp.net mvc 3 MVC 3@Html.DropDownListFor模型绑定失败

Asp.net mvc 3 MVC 3@Html.DropDownListFor模型绑定失败,asp.net-mvc-3,model-binding,html.dropdownlistfor,Asp.net Mvc 3,Model Binding,Html.dropdownlistfor,我正在使用VS2010和MVC3和EF5。我对下拉列表使用了一种通用模式,该模式在除一个实例外的所有实例中都能正常工作,我不明白为什么这个模式无法在选择列表中选择正确的条目。以下是代码片段 选择列表的创建如下所示: public static IEnumerable<SelectListItem> GetOutcomes() { CodesEntities dataContextCodes = new CodesEntities(ConnectionSt

我正在使用VS2010和MVC3和EF5。我对下拉列表使用了一种通用模式,该模式在除一个实例外的所有实例中都能正常工作,我不明白为什么这个模式无法在选择列表中选择正确的条目。以下是代码片段

选择列表的创建如下所示:

   public static IEnumerable<SelectListItem> GetOutcomes()
    {
        CodesEntities dataContextCodes = new CodesEntities(ConnectionString);

        return new SelectList(dataContextCodes.CodeOutcome.
            Where(x => x.DisplayOrder > 0).OrderBy(x => x.DisplayOrder), 
            "OutcomeCodeID", "Outcome");
    }
模型值
m.OutcomeCodeID
具有有效值(1),但未选择任何项

生成的HTML是:

<select id="CodeID" name="OutcomeCodeID" data-val-required="Outcome is required" data-val-number="The field outcome must be a number." data-val="true">
<option value="">Please select an item</option>
<option value="1">Termination</option>
<option value="2">Loss</option>
<option value="3">Still</option>
<option value="4">Live</option>
</select>

请选择一个项目
终止
损失
仍然
居住
我正处于头发撕裂、发疯的阶段。有人有什么想法吗


谢谢

您没有在任何地方设置默认选定值

您用于SelectList的特定构造函数如下所示:

public SelectList(
    IEnumerable items,
    string dataValueField,
    string dataTextField
)
public SelectList(
    IEnumerable items,
    string dataValueField,
    string dataTextField,
    Object selectedValue
)
它不设置默认值。您可以使用以下选项之一:

public SelectList(
    IEnumerable items,
    string dataValueField,
    string dataTextField
)
public SelectList(
    IEnumerable items,
    string dataValueField,
    string dataTextField,
    Object selectedValue
)
并指定selectedValue,或者手动将SelectedListItem在要选择的项目上的Selected属性设置为true(http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlistitem(v=vs.108).aspx)


这是一个无耻的插件,但我仍然认为它是一个很好的资源:

您可以这样做:

public static IEnumerable<SelectListItem> GetOutcomes(string selectedID)
{
    CodesEntities dataContextCodes = new CodesEntities(ConnectionString);


    return new SelectList(dataContextCodes.CodeOutcome.
        Where(x => x.DisplayOrder > 0).OrderBy(x => x.DisplayOrder), 
        "OutcomeCodeID", "Outcome"
        , selectedID); // add this parameter
}
@Html.DropDownListFor(m => m.OutcomeCodeID,
            PerintalFormViewModels.GetOutcomes(Model.OutcomeCodeID), 
            "Please select an item")

您可以发布生成的HTML吗?谢谢,上面添加了生成的HTML。您希望选择什么选项?“请选择一个项目”选项或与当前Id匹配的选项?与当前Id匹配的选项(终止)。您也可以提供模型和控制器操作吗?谢谢Michael,这很好。我仍然不明白为什么原作不起作用,但生活中有点担心它。谢谢芮的上述提示