我正在尝试设置从模型值下拉中选择的值。 有人可以帮忙我可以设置模型值来选择。
@foreach (var item in Model)
{
<p>
@Html.DisplayFor(modelItem => item.Type)
</p>
<p>
@Html.DropDownList("categoryvalues", (IEnumerable<SelectListItem>)ViewBag.Category, "Select")
</p>
}
尝试在下面
@Html.DropDownListFor(modelItem => item.Type, new SelectList((IEnumerable<SelectListItem>)ViewBag.Category,"Value","Text",modelItem => item.Type.ToString()))
我收到错误
无法将lambda表达式转换为'object'类型,因为它不是委托类型
答案 0 :(得分:0)
您需要做的就是提供模型中的值和SelectList
对象:
@Html.DropDownListFor(m => m.Category, Model.CategorySelectList, "Select a category")
其中Category
是模型的属性,而CategorySelectList
是模型上的SelectList
对象。
我建议您在模型中构建SelectList
对象,这样就不会因任何投射或对象构建而使视图混乱。
答案 1 :(得分:0)
我通常在我的控制器内执行此操作:
ViewBag.Category = new SelectList(SelectAllList(),"ID", "NAME",selectedValue);
selectedValue是您要选择的ID。
答案 2 :(得分:0)
如果您正在使用枚举,请在评论中提及,请尝试使用我的枚举帮助....
http://jnye.co/Posts/4/creating-a-dropdown-list-from-an-enum-in-mvc-and-c%23
这将允许您执行以下操作:
在你的控制器中:
//If you don't have an enum value use the type
ViewBag.DropDownList = EnumHelper.SelectListFor<MyEnum>();
//If you do have an enum value use the value (the value will be marked as selected)
ViewBag.DropDownList = EnumHelper.SelectListFor(MyEnum.MyEnumValue);
在您的视图中
@Html.DropDownList("DropDownList")
@* OR *@
@Html.DropDownListFor(m => m.Property, ViewBag.DropDownList as SelectList, null)
这是帮手:
public static class EnumHelper
{
// Get the value of the description attribute if the
// enum has one, otherwise use the value.
public static string GetDescription<TEnum>(this TEnum value)
{
var fi = value.GetType().GetField(value.ToString());
if (fi != null)
{
var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
}
return value.ToString();
}
/// <summary>
/// Build a select list for an enum
/// </summary>
public static SelectList SelectListFor<T>() where T : struct
{
Type t = typeof(T);
return !t.IsEnum ? null
: new SelectList(BuildSelectListItems(t), "Value", "Text");
}
/// <summary>
/// Build a select list for an enum with a particular value selected
/// </summary>
public static SelectList SelectListFor<T>(T selected) where T : struct
{
Type t = typeof(T);
return !t.IsEnum ? null
: new SelectList(BuildSelectListItems(t), "Text", "Value", selected.ToString());
}
private static IEnumerable<SelectListItem> BuildSelectListItems(Type t)
{
return Enum.GetValues(t)
.Cast<Enum>()
.Select(e => new SelectListItem { Value = e.ToString(), Text = e.GetDescription() });
}
}