4

在创建 SelectList 时,是否有一种简单的方法可以删除魔术字符串的使用,例如以下示例:

@Html.DropDownListFor( model => model.FooValue, new SelectList( Model.FooCollection,  "FooId", "FooText", Model.FooValue) )

魔弦是"FooId""FooText"

该示例的其余部分定义如下:

//Foo Class
public class Foo {

  public int FooId { get; set; }
  public string FooText { get; set; }

}    

// Repository
public class MsSqlFooRepository : IFooRepository {

  public IEnumerable<Foo> GetFooCollection( ) {

    // Some database query

  }

}

//View model
public class FooListViewModel {

  public string FooValue { get; set; }
  public IEnumerable<Foo> FooCollection { get; set; }

}

//Controller
public class FooListController : Controller {

  private readonly IFooRepository _fooRepository;

  public FooListController() {

    _fooRepository = new FooRepository();

  }

  public ActionResult FooList() {

    FooListViewModel fooListViewModel = new FooListViewModel();

    FooListViewModel.FooCollection = _fooRepository.GetFooCollection;

    return View( FooListViewModel);

  }

}
4

3 回答 3

3

使用扩展方法和 lambda 表达式的强大功能,您可以这样做:

@Html.DropDownListFor(model => model.FooValue, Model.FooCollection.ToSelectList(x => x.FooText, x => x.FooId))

扩展方法如下:

public static class SelectListHelper
{
    public static IList<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, string> text, Func<T, string> value)
    {
        var items = enumerable.Select(f => new SelectListItem()
        {
            Text = text(f),
            Value = value(f)
        }).ToList();
        items.Insert(0, new SelectListItem()
        {
            Text = "Choose value",
            Value = string.Empty
        });
        return items;
    }
}
于 2011-08-10T14:50:04.877 回答
0

我使用视图模型,因此我的 FooValues 下拉列表具有以下属性:

public SelectList FooValues { get; set; }
public string FooValue { get; set; }

然后在我构建视图模型的代码中:

viewModel.FooValues = new SelectList(FooCollection, "FooId", "FooText", viewModel.FooValue);

然后在我看来:

@Html.DropDownListFor(m => m.FooValue, Model.FooValues)

我希望这有帮助。

于 2011-04-01T14:06:01.053 回答
0

在 C# 6 中,您可以利用nameof并轻松摆脱这些魔术字符串。

... = new SelectList(context.Set<User>(), nameof(User.UserId), nameof(User.UserName));
于 2016-02-01T22:04:20.040 回答