C# 绑定选定值的mvc4动态下拉列表

C# 绑定选定值的mvc4动态下拉列表,c#,asp.net-mvc-4,html-select,C#,Asp.net Mvc 4,Html Select,我用的是MVC4 在控制器端,我有两个列表: 1> 承运人列表:-它包含运输数据列表 2> TransPortationModeList:-它包含所选运输数据的id&它来自数据库 现在,在编辑模式下,我必须做的第一件事是将dropdownlist与“CarrierList”记录绑定。 并选择此列表的属性,该属性的id(值)应来自“TransPortationModeList” 为此,我的视图代码为: @foreach (var Data in Model.TransPortationModeLi

我用的是MVC4

在控制器端,我有两个列表:

1> 承运人列表:-它包含运输数据列表

2> TransPortationModeList:-它包含所选运输数据的id&它来自数据库

现在,在编辑模式下,我必须做的第一件事是将dropdownlist与“CarrierList”记录绑定。 并选择此列表的属性,该属性的id(值)应来自“TransPortationModeList”

为此,我的视图代码为:

@foreach (var Data in Model.TransPortationModeList)
                {

    @Html.DropDownListFor(lm => lm.TransPortationModeList[Model.TransPortationModeList.IndexOf(Data)].TransModeId, Model.CarrierList.Select(c => new SelectListItem { Text = c.TransportationName + "-" + c.TransportationModelID, Value = c.TransportationModelID }), TransPortationModeList[Model.TransPortationModeList.IndexOf(Data)].TransModeId, new { @class = "form-control" })

}
这里:TransPortationModeList[Model.TransPortationModeList.IndexOf(Data)].TransModeId为我提供ID

现在,根据这段代码,我无法为所选记录绑定dropdownlist

请让我知道。我错过了什么


谢谢。

使用
for
循环可以减少冗长,因为您可以避免
IndexOf
用法:

@for(int index = 0; index < Model.TransPortationModeList.Count; index++)
{
    @Html.DropDownListFor(lm => lm.TransPortationModeList[index].TransModeId,
                                Model.CarrierList.Select(c => new SelectListItem { Text = c.TransportationName + "-" + c.TransportationModelID, Value = c.TransportationModelID }), 
                                new { @class = "form-control" })

}
for(int index=0;indexlm.TransPortationModeList[index].TransModeId, Model.CarrierList.Select(c=>new SelectListItem{Text=c.TransportationName+“-”+c.TransportationModelID,Value=c.TransportationModelID}), 新的{@class=“表单控制”}) }
第一个参数将包含所选的值。

如果使用
for
循环,它可以不太冗长,因为您可以避免
IndexOf
用法:

@for(int index = 0; index < Model.TransPortationModeList.Count; index++)
{
    @Html.DropDownListFor(lm => lm.TransPortationModeList[index].TransModeId,
                                Model.CarrierList.Select(c => new SelectListItem { Text = c.TransportationName + "-" + c.TransportationModelID, Value = c.TransportationModelID }), 
                                new { @class = "form-control" })

}
for(int index=0;indexlm.TransPortationModeList[index].TransModeId, Model.CarrierList.Select(c=>new SelectListItem{Text=c.TransportationName+“-”+c.TransportationModelID,Value=c.TransportationModelID}), 新的{@class=“表单控制”}) }
第一个参数将包含所选的值。

您的
数据
属性是如何初始化的?此外,您不必在收集
SelectListItem
后指定
TransModeId
,因为所选值应该由您的第一个参数(
lm=>lm.TransPortationModeList[Model.TransPortationModeList.IndexOf(Data)]提供。TransModeId
)@RédaMattar用于我正在为每个人使用的数据。让我再次更新我的问题。您的
数据
属性是如何初始化的?此外,您不必在收集
SelectListItem
后指定
TransModeId
,因为所选值应该由您的第一个参数(
lm=>lm.TransPortationModeList[Model.TransPortationModeList.IndexOf(Data)]提供。TransModeId
)@RédaMattar用于我正在为每个人使用的数据。让我再次更新我的问题。