从我的 MVC3 应用程序中得到一些非常烦人的行为。所以我有一个具有 3 个值的模型:
[DisplayName("Airlines ")]
[StringLength(2, ErrorMessage = "Airline codes can only be 2 characters in length")]
public string AirlineCode1 { get; set; }
[DisplayName("Airlines")]
[StringLength(2, ErrorMessage = "Airline codes can only be 2 characters in length")]
public string AirlineCode2 { get; set; }
[DisplayName("Airlines")]
[StringLength(2, ErrorMessage = "Airline codes can only be 2 characters in length")]
public string AirlineCode3 { get; set; }
现在这些是从 a 填充的,DropDowList
所以我在中弹出DropDownListItem
sViewBag
并将它们呈现在视图中,例如:
@Html.LabelFor(l => l.AirlineCode1) <span>(select/enter code in box on right)</span>
<div id="airportCode1">
@Html.DropDownListFor(d => d.AirlineCode, ViewBag.AirLines as List<SelectListItem>) <input type="text" maxlength="2" value="@Model.AirlineCode1" />
</div>
<div id="airportCode2" style="@Model.AirlineCode2Style">
@Html.DropDownListFor(d => d.AirlineCode, ViewBag.AirLines2 as List<SelectListItem>) <input type="text" maxlength="2" value="@Model.AirlineCode2" />
</div>
<div id="airportCode3">
@Html.DropDownListFor(d => d.AirlineCode3, ViewBag.AirLines3 as List<SelectListItem>) <input type="text" maxlength="2" value="@Model.AirlineCode3" />
</div>
所以我的控制器看起来像:
IEnumerable<SelectListItem> airLines = PopulateAirlines(user);
ViewBag.AirLines = airLines;
ViewBag.AirLines2 = airLines;
ViewBag.AirLines3 = airLines;
现在在某些情况下,我想AirLineCode
在模型中进行预填充。所以我在控制器中设置模型值。这导致了一些奇怪的行为。突然间,我所有的DropDownList
s都包含了预填充的值!
检查模型,值仅设置在AirLineCode1
. 勾选了ViewBag
,没有选中SelectListItems
。所以我认为ViewBag
必须保持参考。所以我将代码更改为:
ViewBag.AirLines = PopulateAirlines(user);
ViewBag.AirLines2 = PopulateAirlines(user);
ViewBag.AirLines3 = PopulateAirlines(user);
繁荣,固定。问题是PopulateAirlines
一个昂贵的过程!
问题是 ViewBag 似乎在 3SelectListItem
List
秒之间保持参考。我如何阻止它这样做并且仍然只打一个电话PopulateAirlines(user);
?
我尝试了下面的代码,这完全炸毁了:
IEnumerable<SelectListItem> airLines = PopulateAirlines(user);
ViewBag.AirLines = airLines;
ViewBag.AirLines2 = airLines.Select(s => new SelectListItem() { Text = s.Text, Value = s.Value, Selected = s.Selected });
ViewBag.AirLines3 = airLines.Select(s => new SelectListItem() { Text = s.Text, Value = s.Value, Selected = s.Selected });
出现错误:
没有具有键“AirlineCode2”的“IEnumerable”类型的 ViewData 项。
什么??!