【发布时间】:2014-07-22 23:16:31
【问题描述】:
我正在使用带有 EF6 的 MVC5。我需要在一个视图中创建几十个下拉列表,其中包含用户可选择的首选项,然后在整个 Web 应用程序中使用这些首选项。
我遇到的问题是剃刀视图中的 LabelFor 和 DropdownListFor 行都有错误:
编译器错误消息:CS0411:无法从中推断方法“System.Web.Mvc.Html.LabelExtensions.LabelFor System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>, string)”的类型参数用法。尝试明确指定类型参数。
我已经跟踪了我的代码以确保Model.Preferences 包含我想要的数据,并且确实如此。实际上,它与Html.Label 和Html.DropdownList 一起工作得很好,但我无法让所选项目以这种方式工作,所以我切换到DropdownListFor,因为我发现在这方面更容易使用。
这是我的代码的 sn-ps(正在进行中):
一个简单的类来保存 SelectListItem 的 IEnumerable:
public class Preference
{
public string ControlType; // "Select", "Textbox"
public string Label; // Label of control
public IEnumerable<SelectListItem> ListItems;
}
MODEL(一个 IEnumerable 的 Preference 给了我“Preferences”)
public class UserPreferencesViewModel
{
public IEnumerable<Preference> Preferences { get; set; }
}
控制器
List<Preference> Preferences = new List<Preference>();
foreach (var g in uomGroups)
{
List<SelectListItem> listitems = new List<SelectListItem>();
foreach (var w in g.Options)
{
... Omitted for brevity ...
listitems.Add( new SelectListItem { Text = w.UOMId, Value = w.UOMId, Selected = isSelected } )
}
var p = g.Options.ToArray();
Preferences.Add( new Preference
{
ControlType = "Select",
Label = g.Preference,
ListItems = listitems
});
}
model.Preferences = Preferences.AsEnumerable();
return View(model);
查看
<tbody>
@foreach (Preference preference in Model.Preferences)
{
<tr>
<td>
@Html.LabelFor(
x => x.Label,
new { @class = "col-md-3 control-label" }
)
</td>
<td>
@Html.DropDownListFor(
x => x.Label,
new SelectList(preference.ListItems, "Value", "Text"),
new { @class = "col-md-3 form-control" }
)
</td>
</tr>
}
</tbody>
从上面的代码中,有没有人看出问题出在哪里?我一直试图弄清楚这个几个小时,只是没有看到它。
【问题讨论】:
标签: asp.net-mvc linq razor