ASP .NET MVC 3 DropDownListFor问题

时间:2011-08-08 16:26:16

标签: asp.net-mvc razor html-helper

在模型中,我有:

public Guid? Country
{ get; set; }

在视图中,我有:

@Html.DropDownListFor(m => m.Country, (SelectList)ViewBag.Countries)

提交时,出现错误,导致它想要将字符串保存到Guid。如何保存值而不是下拉列表的文本?

1 个答案:

答案 0 :(得分:2)

确定。得到了一些不同的方法。

型号:

public UserRegistrationModel()
{
    this.InitializeCountries();
}

private void InitializeCountries()
{
    FarmerEntities fe = new FarmerEntities();
    var query = from c in new FarmerEntities().Countries select new { ID = c.ID_Country, Name = c.ISO_Code };
    var countries = query.ToSelectList(c => c.ID.ToString(), c => c.Name);

    this.Countries = countries;
}

public Guid? { get; set; }

public IEnumerable<SelectListItem> Countries
{ get; set; }

控制器:

UserRegistrationModel model = new UserRegistrationModel();

return View(model);

查看:

@Html.DropDownListFor(m => m.Country, Model.Countries, "")

此外,您需要实现此扩展程序

public static class EnumerableExtensions
{
    public static IEnumerable<SelectListItem> ToSelectList<TItem, TValue>(this IEnumerable<TItem> items, Func<TItem, TValue> valueSelector, Func<TItem, string> nameSelector)
    {
        return items.ToSelectList(valueSelector, nameSelector, x => false);
    }

    public static IEnumerable<SelectListItem> ToSelectList<TItem, TValue>(this IEnumerable<TItem> items, Func<TItem, TValue> valueSelector, Func<TItem, string> nameSelector, IEnumerable<TValue> selectedItems)
    {
        return items.ToSelectList(valueSelector, nameSelector, x => selectedItems != null && selectedItems.Contains(valueSelector(x)));
    }

    public static IEnumerable<SelectListItem> ToSelectList<TItem, TValue>(this IEnumerable<TItem> items, Func<TItem, TValue> valueSelector, Func<TItem, string> nameSelector, Func<TItem, bool> selectedValueSelector)
    {
        foreach (var item in items)
        {
            var value = valueSelector(item);

            yield return new SelectListItem
            {
                Text = nameSelector(item),
                Value = value.ToString(),
                Selected = selectedValueSelector(item)
            };
        }
    }
}