yavsc/src/Yavsc.Org/Helpers/PageHelpers.cs
Paul Schneider 40e8e08690 reorg
2026-02-28 21:17:54 +00:00

52 lines
2 KiB
C#
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Localization;
namespace Yavsc.Server.Helpers
{
public static class PageHelpers
{
public static List<SelectListItem> CreateSelectListItems<T> (this IStringLocalizer<T> localisation, Type enumType, object selectedValue =null)
{
string selectedName = (selectedValue != null) ? enumType.GetEnumName(selectedValue) : null;
var items = new List<SelectListItem> ();
var names = enumType.GetEnumNames();
var values = enumType.GetEnumValues();
for (int index = 0; index < names.Length; index++)
{
var itemName = names[index];
items.Add(new SelectListItem() {
Value = values.GetValue(index).ToString(), Text = localisation[itemName], Selected = ( itemName == selectedName)
}) ;
}
var list = new SelectList(items);
return items;
}
public static List<SelectListItem> AddNull(this List<SelectListItem> selectList, string displayNull, object selectedValue = null)
{
selectList.Add(new SelectListItem { Text = displayNull, Value = "", Selected = selectedValue == null });
return selectList;
}
public static List<SelectListItem> CreateSelectListItems<T> (this IEnumerable<T>data,
Func<T,string> dataField,
Func<T,string> displayField = null, object selectedValue =null) where T : class
{
if (displayField == null) displayField = dataField;
var items = new List<SelectListItem> ();
foreach (var dataItem in data)
{
var itemVal = dataField(dataItem);
var itemName = displayField(dataItem);
items.Add(new SelectListItem() {
Value = itemVal, Text = itemName, Selected = ( selectedValue?.Equals(itemVal) ?? false )
}) ;
}
return items;
}
}
}