Search code examples
c#linqdrop-down-menuhtml-encode

LINQ to DropDownList with Server.HtmlDecode


I have this code which uses LINQ to populate a DropDownList:

var userCategories = DataAccessLayer.Context.Categories
    .Where(c => c.UserName == HttpContext.Current.User.Identity.Name)
    .Select(c => new { c.ID, c.Category })
    .OrderBy(c => c.Category);

CategoryDropDownList.DataSource = userCategories;

CategoryDropDownList.DataValueField = "ID";

CategoryDropDownList.DataTextField = "Category";

CategoryDropDownList.DataBind();

Where would I put the Server.HtmlDecode for Category?


Solution

  • First, you want HtmlEncode, not HtmlDecode. Here's an example:

    foreach (var category in userCategories)
    {
        CategoryDropDownList.Items.Add(new ListItem(Server.HtmlEncode(category.Category), category.ID.ToString()));
    }