65 lines
2.0 KiB
C#
65 lines
2.0 KiB
C#
using Microsoft.AspNetCore.Html;
|
|
using System.Collections;
|
|
|
|
namespace YLErp.Web
|
|
{
|
|
public static class HtmlExtensions
|
|
{
|
|
/// <summary>
|
|
/// 序列化对象到htmlstring,处理了对象为null时的情况
|
|
/// </summary>
|
|
public static IHtmlContent JsonSerialize<T>(this IHtmlHelper helper, T value, bool ignoreNullValue = true, bool camelCase = false)
|
|
{
|
|
if (value == null)
|
|
{
|
|
var type = typeof(T);
|
|
var untype = Nullable.GetUnderlyingType(type);
|
|
if (untype != null)
|
|
{
|
|
type = untype;
|
|
}
|
|
if (type.IsValueType)
|
|
{
|
|
var val = Activator.CreateInstance(type);
|
|
return new HtmlString(JsonHelper.ToJson(val));
|
|
}
|
|
if (type.IsArray || typeof(IEnumerable).IsAssignableFrom(type))
|
|
{
|
|
return new HtmlString("[]");
|
|
}
|
|
return new HtmlString("{}");
|
|
}
|
|
|
|
return new HtmlString(JsonHelper.ToJson(value, ignoreNullValue, camelCase));
|
|
}
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
public static SelectListItem AsSelectListItem(this SelectItem selectItem)
|
|
{
|
|
return selectItem != null ? new SelectListItem
|
|
{
|
|
Disabled = selectItem.Disabled,
|
|
Selected = selectItem.Selected,
|
|
Text = selectItem.Text,
|
|
Value = selectItem.Value
|
|
} : null;
|
|
}
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
public static List<SelectListItem> AsSelectListItems(this IEnumerable<SelectItem> selectItems)
|
|
{
|
|
return selectItems?.Select(n => new SelectListItem
|
|
{
|
|
Disabled = n.Disabled,
|
|
Selected = n.Selected,
|
|
Text = n.Text,
|
|
Value = n.Value
|
|
}).ToList();
|
|
}
|
|
}
|
|
}
|