开发者

Using SelectList without magic strings

Is there an easy way to remove the use of Magic Strings when creating a SelectList, like in this example:

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

The magic strings being "FooId" and "FooText"

The rest of the example is defined as follows:

//Foo Class
public class Foo {

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

}    

// Repository
public class MsSqlFooRepository : IFooRepos开发者_如何学Pythonitory {

  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);

  }

}


Using an extension method and the power of lambda expressions, you can do this:

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

The extension method is as follows:

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;
    }
}


I use View Models so I have the following properties for my FooValues dropdown:

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

and then in my code for building my view model I do:

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

Then in my view:

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

I hope this helps.


In C# 6 you can take advantage of nameof and easily get rid of these magic strings.

... = new SelectList(context.Set<User>(), nameof(User.UserId), nameof(User.UserName));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜